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
You can make use of array.reduce
method to convert an original array into a new array with desired structure.
We can just check if the id exists in the array and accordingly update the array with new object having count property.
let arr = [{
id: 1
}, {
id: 1
}, {
id: 1
}, {
id: 2
}, {
id: 2
}];
let new_arr = arr.reduce((ar, obj) => {
let bool = false;
if (!ar) {
ar = [];
}
ar.forEach((a) => {
if (a.id === obj.id) {
a.count++;
bool = true;
}
});
if (!bool) {
obj.count = 1;
ar.push(obj);
}
return ar;
}, []);
console.log(new_arr);