I have an array of javascript objects that are products. These products are displayed in a list as a cart.
I want to count the number of duplicate products in the ar
The easiest would be probably a map:
var map=new Map();
names.forEach(function(el){
if(map.has(el["_id"])){
map.get(el["_id"]).count++;
}else{
map.set(el["_id"],Object.assign(el,{count:1}));
}
});
And then recreate an array:
names=[...map.values()];
Or in old hash/array way:
var hash={},result=[];
names.forEach(function(name){
var id=name["_id"];
if(hash[id]){
hash[id].count++;
}else{
result.push(hash[id]={
count:1,
...name
});
}
});
console.log(result);