如何通过对ID进行分组来创建数组的数组

时间:2019-01-26 09:32:57

标签: javascript

我有一个数组:

let array = [{id: 1, name:'a'}, {id: 2, name: 'b'},{id: 1, name:'c'}];

我想要一个像这样的数组

arr2 = [[{id: 1, name:'a'}, {id: 1, name:'c'}], [{id: 2, name: 'b'}]]

我尝试了此操作,但是找不到添加到哪个数组:

 $scope.journalsArray = response.data.body.Data;
      $scope.newArray = [];
      let idsArray = [];
      for (let i = 0; i < $scope.journalsArray.length; i++) {
         if(idsArray.indexOf($scope.journalsArray[i].journal_id) != -1){
          $scope.newArray.push($scope.journalsArray[i]);
         }else{
           $scope.idsArray.push($scope.journalsArray[i].journal_id);
         }
      } 

5 个答案:

答案 0 :(得分:1)

  • Array.reduce覆盖原始阵列。
  • 如果存在一个具有相同id的项目的组,则将其推入。
  • 否则,创建组。

let array = [{id: 1, name:'a'}, {id: 2, name: 'b'},{id: 1, name:'c'}]
let result = array.reduce((acc, item) => {
  const group = acc.find(group => group.find(inner => inner.id === item.id))
  
  if (group) 
   group.push(item)
  else
   acc.push([item])
   
  return acc
}, [])

console.log(result)

答案 1 :(得分:1)

使用 reduce(),find()和filter()方法可以实现这一目标

let array = [
    {id: 1, name:'a'},
    {id: 2, name: 'b'},
    {id: 1, name:'c'}
];

const results = arr => {
    return arr.reduce((result, item ) => {
        if (!result.find(obj => obj[0].id === item.id)) {
            result.push(array.filter(val => val.id == item.id))   
        }
        return result;
    }, [])
}
console.log(results(array));

// ​​​​​[ [ { id: 1, name: 'a' }, { id: 1, name: 'c' } ], [ { id: 2, name: 'b' } ] ]​​

答案 2 :(得分:0)

您可以使用Map并将对象收集在同一组中。然后获取每个组的值作为结果。

var array = [{ id: 1, name:'a' }, { id: 2, name: 'b' },{ id: 1, name:'c' }],
    result = Array.from(
        array
            .reduce((m, o) => m.set(o.id, [...(m.get(o.id) || []), o]), new Map)
            .values()
    );

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 3 :(得分:0)

使用Array#reduce,Map,解构和Array#concat。

const data = [{id: 1, name:'a'}, {id: 2, name: 'b'},{id: 1, name:'c'}];

const res = data.reduce((a,{id,name})=>{
  return a.set(id, [{id,name}].concat(a.get(id)||[]));
}, new Map()).values();

console.log([...res]);

答案 4 :(得分:0)

let array = [{id: 1, name:'a'}, {id: 2, name: 'b'},{id: 1, name:'c'}]
let result = array.reduce((acc, item) => {
  const group = acc.find(group => group.find(inner => inner.id === item.id))
  
  if (group) 
   group.push(item)
  else
   acc.push([item])
   
  return acc
}, [])

console.log(result)

let array = [{id: 1, name:'a'}, {id: 2, name: 'b'},{id: 1, name:'c'}]
let result = array.reduce((acc, item) => {
  const group = acc.find(group => group.find(inner => inner.id === item.id))
  
  if (group) 
   group.push(item)
  else
   acc.push([item])
   
  return acc
}, [])

console.log(result)