Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
916 views
in Technique[技术] by (71.8m points)

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

问题描述

初衷是根据把相同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'}]


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

直接上代码吧~

const handleArr = arr => {
  let result = {}
  let currIndex = 0
  arr.reduce((prev, curr) => {
    if (prev.id === curr.id) {
      result[`arr${currIndex}`].push(curr)
    } else {
      currIndex++
      result[`arr${currIndex}`] = [curr]
    }
    return curr
  }, {})
  return result
}
console.log(handleArr(arr))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...