首页 > 解决方案 > 如何删除数组中的重复项?

问题描述

我有以下物品。我想删除重复的项目并返回数组。我尝试过使用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;
  }

标签: javascript

解决方案


你正在使用const和其他 ES6 特性,所以你应该可以使用一个Set就好了。您可能遇到的问题是两个数组不相等,因此将数组放入 aSet不会删除内部数组。相反,您可以将数组中的每个内部数组映射到一个字符串,这样您就可以使用 aSet删除重复项,然后使用Array.fromwithJSON.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);


推荐阅读