我有这个样本数据集:
let list = [
{'first': 'morgan', 'id': 1},
{'first': 'eric', 'id': 1},
{'first': 'brian', 'id': 2 },
{'first': 'derek', 'id' : 2},
{'first': 'courtney', 'id': 3},
{'first': 'eric', 'id': 4},
{'first': 'jon', 'id':4},
]
我正在尝试得到这个结果:
[[1, [morgan, eric]], [2, [brian, derek]], [3, [courtney]], [4, [eric, jon]]
我正在使用.reduce()
函数来映射列表。然而,我有些卡住了。
我已经做到了这一点:
let b = list.reduce((final_list, new_item) => {
x = final_list.concat([[new_item.id, [new_item.first]]])
return x
}, [])
然而,这样会将列表扁平化为列表的列表,但不会合并共享相似id的名称。
我尝试使用.map()
下面的代码不起作用
我尝试对final_list(这是一个[id,[names]]列表)进行映射,查看new_item
的id是否存在于smaller_list
中,然后将new_item.first
添加到smaller_list [1]
(应该是名称列表)。
这是正确的方法吗?
let b = list.reduce((final_list, new_item) => {
final_list.map((smaller_list) => {
if (smaller_list.indexOf((new_item.id)) >=0) {
smaller_list[1].concat(new_item.first)
// not sure what to do here...
} else {
// not sure what to do here either...
}
})
x = final_list.concat([[item.id, [item.first]]])
return x
}, [])
temp
应该是一个数组吗? - Philtemp
在位置0
会有一个undefined
的条目。看起来forEach
不会包括它或者任何其他索引中的间隙。今天我学到了这个。 - Phil