如何对数组中的重复对象进行分组

时间:2022-08-27 18:08:33

Take for example this array:

以这个数组为例:

 [{id: 0, weight: 200}
 {id: 0, weight: 200}
 {id: 1, weight: 75}
 {id: 2, weight: 5}]

I need to get it a result of :

我需要得到它的结果:

[  {id:0, times:2},
   {id:1, times:1},
   {id:2, times:1}]

2 个解决方案

#1


1  

var array= [
 {id: 0, weight: 200},
 {id: 0, weight: 200},
 {id: 1, weight: 75},
 {id: 2, weight: 5}];

console.log(array.reduce((function(hash){
return function(array,obj){
 if(!hash[obj.id])
  array.push(hash[obj.id]={id:obj.id,times:1});
 else
   hash[obj.id].times++;
  return array;
  };    
})({}),[]));

See Combine multiple arrays by same key for an explanation and you can try it here :http://jsbin.com/licuwadifa/edit?console.

请参阅使用相同的键组合多个阵列以获得解释,您可以在此处尝试:http://jsbin.com/licuwadifa/edit?console。

#2


1  

You could reduce the array into a new array with the count

您可以使用计数将数组缩减为新数组

var arr = [
    { id: 0, weight: 200 }, 
    { id: 0, weight: 200 }, 
    { id: 2, weight: 75  }, 
    { id: 9, weight: 5   }
];

var arr2 = arr.reduce( (a,b) => {
    var i = a.findIndex( x => x.id === b.id);
    return i === -1 ? a.push({ id : b.id, times : 1 }) : a[i].times++, a;
}, []);

console.log(arr2)

#1


1  

var array= [
 {id: 0, weight: 200},
 {id: 0, weight: 200},
 {id: 1, weight: 75},
 {id: 2, weight: 5}];

console.log(array.reduce((function(hash){
return function(array,obj){
 if(!hash[obj.id])
  array.push(hash[obj.id]={id:obj.id,times:1});
 else
   hash[obj.id].times++;
  return array;
  };    
})({}),[]));

See Combine multiple arrays by same key for an explanation and you can try it here :http://jsbin.com/licuwadifa/edit?console.

请参阅使用相同的键组合多个阵列以获得解释,您可以在此处尝试:http://jsbin.com/licuwadifa/edit?console。

#2


1  

You could reduce the array into a new array with the count

您可以使用计数将数组缩减为新数组

var arr = [
    { id: 0, weight: 200 }, 
    { id: 0, weight: 200 }, 
    { id: 2, weight: 75  }, 
    { id: 9, weight: 5   }
];

var arr2 = arr.reduce( (a,b) => {
    var i = a.findIndex( x => x.id === b.id);
    return i === -1 ? a.push({ id : b.id, times : 1 }) : a[i].times++, a;
}, []);

console.log(arr2)