gpt4 book ai didi

javascript - 如何删除数组中的重复项?

转载 作者:行者123 更新时间:2023-11-28 14:14:35 26 4
gpt4 key购买 nike

我有以下元素。我想删除重复的项目并返回数组。我尝试过使用 Set 但我认为这不是我当前使用的 Ecma 脚本的一部分。我知道这个问题已经在这里被问过多次,但我似乎无法让我的工作发挥作用。

0: (2) [0, 2]

1: (2) [0, 2]

2: (2) [1, 2]

3: (2) [1, 3]

 function checkDuplicate(array: any, obj: any) {
const exists = array.some((o: any) => o.itemOne === obj.itemOne && o.itemTwo === obj.itemTwo);
if (exists) {
return true;
} else {
return false;
}
}

function check() {
const testArray: any = [];
arrayOne().map((item: any) => {
arrayTwo().map((item2: any) => {
if (item.someMatchingValue === item2.someMatchingValue) {
if (!checkDuplicate(testArray, [item.itemOne, item2.itemTwo])) {
testArray.push([item.itemOne, item2.itemTwo]);
}
}
});
});
console.log(testArray);
return testArray;
}

最佳答案

您正在使用 const 和其他 ES6 功能,因此您应该能够很好地使用 Set 。您可能遇到的问题是两个数组不相等,因此将数组放入 Set 中不会删除内部数组。相反,您可以将数组中的每个内部数组映射到一个字符串,这样您就可以使用 Set 删除重复项,然后将 Array.from 一起使用JSON.parse 将字符串 Set 转换回数组数组,如下所示:

const arr = [[0, 2], [0, 2], [1, 2], [1, 3]];

const res = Array.from(new Set(arr.map(JSON.stringify)), JSON.parse);
console.log(res);

关于javascript - 如何删除数组中的重复项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58072754/

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