【发布时间】:2021-10-30 16:01:21
【问题描述】:
我有一个对象数组
const data = [{
productId: 7000254,
quantity: 1
}, {
productId: 7000255,
quantity: 1
}, {
productId: 7000256,
quantity: 1
}, {
productId: 7000257,
quantity: 1
}, {
productId: 7000254,
quantity: 1
}];
我需要使用 reduce 函数从中获取唯一值。
我用下面的代码做的
data.map((rp) => {
if (products.map(({ productId }) => productId).indexOf(rp.productId) === -1) {
products.push({ productId: parseInt(rp.productId), quantity: 1 })
}
})
但正如您所见,这是一个漫长的过程,因为我必须多次迭代数组。那么有没有办法使用reduce函数呢?
var unique = data.reduce((a, b ,c,d) => {
if (a.map(({productId}) => productId).indexOf(b.productId) === -1) {
return [a,b]
}
})
console.log(unique)
预期输出
0: {productId: 7000254, quantity: 1}
1: {productId: 7000255, quantity: 1}
2: {productId: 7000256, quantity: 1}
3: {productId: 7000257, quantity: 1}
【问题讨论】:
标签: javascript arrays unique reduce