gpt4 book ai didi

javascript - JS - 数组中的重复元素

转载 作者:行者123 更新时间:2023-11-30 16:02:43 27 4
gpt4 key购买 nike

好吧,我无法解释我要做什么。但我可以解释代码。

我有这个数组:

var array = [{name:"John",lastname:"Doe"},{name:"Alex",lastname:"Bill"},{name:"John",lastname:"Doe"}]

数组包含 2 个重复的元素,我想要一个只显示一次元素重复的函数

当你应用函数时,这将是数组的结果

var array = [{name:"John",lastname:"Doe"},{name:"Alex",lastname:"Bill"}]

最佳答案

你可以用javascript来实现filter以老式方式运行。

var array = [{name:"John",lastname:"Doe"},{name:"Alex",lastname:"Bill"},{name:"John",lastname:"Doe"}]
var names = [];

array = array.filter(function (person) {
var fn = person.name + '-' + person.lastname;
if (names.indexOf(fn) !== -1) {
return false;
}
else {
names.push(fn);
return true;
}
});

console.log(array);
// [{"name":"John","lastname":"Doe"},{"name":"Alex","lastname":"Bill"}]

关于javascript - JS - 数组中的重复元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37473808/

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