这题如何实现比较好
資深大佬 : pyplayer 1
把 id 一样的合并
var array = [ { id: 1, spec: 1 }, { id: 5, spec: 2 }, { id: 2, spec: 5 }, { id: 2, spec: 10 }, { id: 1, spec: 12 }, { id: 3, spec: 12 }, { id: 4, spec: 15 }, { id: 3, spec: 16 } ] 转变为 [ { id: 1, spec: [ 1, 12 ] }, { id: 5, spec: [ 2 ] }, { id: 2, spec: [ 5, 10 ] }, { id: 3, spec: [ 12, 16 ] }, { id: 4, spec: [ 15 ] } ]
自己的思路似乎很烦 大概思路是出现过得 id 添加到了 idarray 里,然后迭代数组每一项,id 出现过就创建一个新对象,没有就选出那个对象往数组后面添加东西
function arrayChange(array){ let idArray = [] let newArray = [] for (let index = 0; index < array.length; index++) { const element = array[index]; if (idArray.includes(element.id)) { let curEle = newArray.filter(item => item.id === element.id) curEle[0].spec.push(element.spec) } else { idArray.push(element.id) let obj = {} obj.id = element.id obj.spec = [] obj.spec.push(element.spec) newArray.push(obj) } } return newArray } console.log(arrayChange(array))
大佬有話說 (10)