一个数组对象,不打扰排序,拆分成多个数组

问题描述

初衷是根据把相同id的对象丢到一个新数组里,然后如果遇到id不同的就停止,如此反复

相关代码

arr = [
{id:1,name:'a'},
{id:1,name:'a1'},
{id:1,name:'a2'},
{id:2,name:'b'},
{id:1,name:'c'},
{id:2,name:'d'},
{id:2,name:'d1'},
{id:1,name:'e'}
]

想根据id拆分成如下数组
arr1 = [{id:1,name:'a'},{id:1,name:'a1'},{id:1,name:'a2'}]
arr2 = [{id:2,name:'b'}]
arr3 = [{id:1,name:'c'}]
arr4 = [{id:2,name:'d'},{id:2,name:'d1'}]
arr5 = [{id:1,name:'e'}]

最佳答案

直接甩代码

let obj = {};
function findFilter(arr, index = 1) {
  obj['arr' + index] = [];
  let id = null;
  let idNext = null;
  for (let i = 0; i < arr.length; i++) {
    id = arr[i].id;
    obj['arr' + index].push(arr[i])
    if (arr[i + 1]) {
      idNext = arr[i + 1].id;
      if (id !== idNext) {
        findFilter(arr.slice(i+1), ++index)
        break
      }
    }
  }
}

findFilter(arr)
console.log(obj)
/** 
{ arr1: 
   [ { id: 1, name: 'a' },
     { id: 1, name: 'a1' },
     { id: 1, name: 'a2' } ],
  arr2: [ { id: 2, name: 'b' } ],
  arr3: [ { id: 1, name: 'c' } ],
  arr4: [ { id: 2, name: 'd' }, { id: 2, name: 'd1' } ],
  arr5: [ { id: 1, name: 'e' } ] 
}
*/