gpt4 book ai didi

javascript - 从数组中仅删除一个相同的对象

转载 作者:行者123 更新时间:2023-12-02 19:32:38 25 4
gpt4 key购买 nike

var array = [{id :1, name :"test1"},{id :2, name :"test2"},{id :2, name :"test2"},{id :3, name :"test3"},{id :4, name :"test4"}];

var anotherOne = [{id :2, name :"test2"}, {id :4, name :"test4"}];

var filteredArray = array.filter(function(array_el){
return anotherOne.filter(function(anotherOne_el){
return anotherOne_el.id == array_el.id;
}).length == 0
});

此代码删除所有“id:2”对象。就像这样做:

{id :1, name :"test1"},{id :3, name :"test3"}

但我只想删除一个相同的对象。像这样:

{id :1, name :"test1"},{id :2, name :"test2"},{id :3, name :"test3"}

但是如果数组的 anotherOne 有两个相同的对象,则需要两个删除。

最佳答案

你可以尝试这个:我正在使用 reducefindIndex 解决这个问题。

var array = [{id :1, name :"test1"},{id :2, name :"test2"},{id :2, name :"test2"},{id :3, name :"test3"},{id :4, name :"test4"}];
var anotherOne = [{id :2, name :"test2"}, {id :4, name :"test4"}];

const res = array.reduce((a, c) => {
const index = anotherOne.findIndex(item => item.id === c.id);

if (index > -1) {
/**
* Remove the matched one from the `anotherOne` array,
* So that you don't have to match it second time.
* So it removes the match one once.
*/
anotherOne.splice(index, 1);
} else {
a.push(c);
}

return a;
}, []);

console.log(res);
.as-console-wrapper {min-height: 100%!important; top: 0;}

关于javascript - 从数组中仅删除一个相同的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61572661/

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