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

后端 未结 3 741
-上瘾入骨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:22

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

提交回复
热议问题