gpt4 book ai didi

javascript - 根据多个键的重复值从对象数组中删除元素

转载 作者:数据小太阳 更新时间:2023-10-29 03:48:28 25 4
gpt4 key购买 nike

我有一个像这样的对象数组 -

var arr = [
{ type_id: "3", full_empty:"true", quantity:1},
{ type_id: "3", full_empty:"true", quantity:1},
{ type_id: "9", full_empty:"true", quantity:4},
{ type_id: "9", full_empty:"false", quantity:4},
{ type_id: "9", full_empty:"true", quantity:4},
{ type_id: "9", full_empty:"true", quantity:4},
{ type_id: "9", full_empty:"true", quantity:4}
];

我想删除具有相同 type_idfull_empty 值的重复项。结果应该是这样的 -

var arr = [
{ type_id: "3", full_empty:"true", quantity:1},
{ type_id: "9", full_empty:"true", quantity:4},
{ type_id: "9", full_empty:"false", quantity:4},
];

我已经搜索并找到了一些解决方案,但其中一些是用于删除重复键或仅基于一个键的重复值删除重复项。一些需要外部库。还有一些我无法理解的解决方案。有没有简单的方法可以在纯 JavaScript 中执行此操作?

编辑以便更好地理解 - 我已阅读此 question .该问题的公认答案是仅查找一个键的重复项。就我而言,我必须找到多个键的重复项。

最佳答案

您可以使用 Array.some() 来使用纯函数 Array.reduce() 将您的输入数组减少为不同元素的数组,如下所示

    var arr = [
{ type_id: "3", full_empty:"true", quantity:1},
{ type_id: "3", full_empty:"true", quantity:1},
{ type_id: "9", full_empty:"true", quantity:4},
{ type_id: "9", full_empty:"false", quantity:4},
{ type_id: "9", full_empty:"true", quantity:4},
{ type_id: "9", full_empty:"true", quantity:4},
{ type_id: "9", full_empty:"true", quantity:4}
];

var a = arr.reduce(function (accumulator, current) {
if (checkIfAlreadyExist(current)) {
return accumulator
} else {
return accumulator.concat([current]);
}

function checkIfAlreadyExist(currentVal) {
return accumulator.some(function(item){
return (item.type_id === currentVal.type_id &&
item.full_empty === currentVal.full_empty);
});
}
}, []);

console.log(a);

简洁的 ES6 语法

可以使用 ES6 箭头函数和扩展运算符编写更简洁的 reduce,如下所示:

var arr = [
{ type_id: "3", full_empty:"true", quantity:1},
{ type_id: "3", full_empty:"true", quantity:1},
{ type_id: "9", full_empty:"true", quantity:4},
{ type_id: "9", full_empty:"false", quantity:4},
{ type_id: "9", full_empty:"true", quantity:4},
{ type_id: "9", full_empty:"true", quantity:4},
{ type_id: "9", full_empty:"true", quantity:4}
];

var a = arr.reduce((accumulator, current) => {
if (checkIfAlreadyExist(current)) {
return accumulator;
} else {
return [...accumulator, current];
}

function checkIfAlreadyExist(currentVal) {
return accumulator.some((item) => {
return (item.type_id === currentVal.type_id &&
item.full_empty === currentVal.full_empty);
});
}
}, []);

console.log(a);

关于javascript - 根据多个键的重复值从对象数组中删除元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38046236/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com