Javascript - Counting duplicates in object array and storing the count as a new object

后端 未结 3 742
-上瘾入骨i
-上瘾入骨i 2020-12-03 20:01

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

3条回答
  •  渐次进展
    2020-12-03 20:10

    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);

提交回复
热议问题