把 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))
![]() | 1 ynohoahc 2020-05-28 19:23:10 +08:00 ![]() |
![]() | 2 jmc891205 2020-05-28 19:29:46 +08:00 via iPhone 额 js 没有 hashmap 一类的东西吗 |
![]() | 4 rabbbit 2020-05-28 19:34:40 +08:00 ![]() function solution(arr) { const table =new Map(); for (const {id, spec} of arr) { if (!table.has(id)) table.set(id, []); table.get(id).push(spec); } const result = []; for (const [id, spec] of table.entries()) { result.push({id, spec}) } return result; } |
![]() | 6 rabbbit 2020-05-28 19:46:57 +08:00 function solution(arr) { const table =new Map(); for (const {id, spec} of arr) { if (!table.has(id)) table.set(id, []); table.get(id).push(spec); } return [...table].map(([id, spec]) => ({id, spec})); } |
7 haha370104 2020-05-28 19:50:54 +08:00 ![]() Object.entries( array.reduce((previousValue, currentValue) => { previousValue[currentValue.id] = ( previousValue[currentValue.id] || [] ).concat(currentValue.spec) return previousValue }, {}) ).map(([id, spec]) => ({ id, spec })) 这应该是我能想出来最短的写法了…… |
9 linZ 2020-05-28 19:53:39 +08:00 用个 Map 不好么。。。rabit 的写法就好了 |