javascript - 如何删除数组中的重复项?
问题描述
我有以下物品。我想删除重复的项目并返回数组。我尝试过使用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
就好了。您可能遇到的问题是两个数组不相等,因此将数组放入 aSet
不会删除内部数组。相反,您可以将数组中的每个内部数组映射到一个字符串,这样您就可以使用 aSet
删除重复项,然后使用Array.from
withJSON.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);
推荐阅读
- reactjs - 使用 SWR 单击时向 API 路由发出请求时出现过多的重新渲染错误
- react-native - React Native 无法识别导入
- c++ - 检查定义中的条件语句
- ansible - 无法使用 ansible zypper 命令安装 rpm 包
- activemq-artemis - ActiveMQ Artemis 中的队列过滤器应该采用什么格式?
- python-3.x - 在涉及灵活 dt 和角速度成本的 2 个四元数之间使用反向欧拉进行优化
- reactjs - NextJS 和 fetch 拦截器随机工作
- mule - 如何在 Mule Any point Studio 7x 中安装 Kafka 连接器**手动**?
- apache-flink - AggregateFunction 中合并方法的含义
- javascript - 在渲染反应钩子之前等待 API 数据