javascript - 使用reduce函数从对象数组中获取唯一值
问题描述
我有一个对象数组
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}
解决方案
您可以使用filter和Set有效地实现此结果。
const data = [{
productId: 7000254,
quantity: 1,
},
{
productId: 7000255,
quantity: 1,
},
{
productId: 7000256,
quantity: 1,
},
{
productId: 7000257,
quantity: 1,
},
{
productId: 7000254,
quantity: 1,
},
];
const set = new Set();
const result = data.filter((o) => {
if (set.has(o.productId)) return false;
set.add(o.productId);
return true;
});
console.log(result);
/* This is not a part of answer. It is just to give the output fill height. So IGNORE IT */
.as-console-wrapper {
max-height: 100% !important;
top: 0;
}
推荐阅读
- android - 将相同的键解析为 kotlin 中的数据类但具有不同的值
- jquery - Jquery-Ui 自动完成跳过表达式“+”和“-”
- javascript - 等到所有请求调用都返回后再继续
- javascript - 如何在我的网站中使用第三方模块进行反应?
- amazon-web-services - AWS Lambda 与 ElasticSearch / Kibana 的连接耗时超过 1.5 秒
- spring-data-redis - Spring Gateway Redis 会话存储类型 - 保存问题
- apache-spark - 如何使用 spark 使 Impala 的元数据无效?
- php - PHP将字符串值从特定位置替换为字符串中的第一个特殊字符
- anaconda - 如何在 linux 中为 Scaled-YOLOv4 设置环境
- azure-devops - 天蓝色管道的其他阶段不可用的动态变量