如何去除数组中的重复数据

Infrequently Noted / 2023-07-25 / 原文

数组去重的方法有很多,这里列举几个常用的方法。

Set对象

Set是一个集合对象,它不包含重复数据,利用这个特性可以很容易实现去除重复数据的效果:

function unique(array = []) {
    return [...new Set(array)];
}

散列表

散列表非常适合用于检查数据的存在性,我们定义一个散列表,遍历过程中,如果数组的元素不存在散列表中,就将元素作为key添加到散列表中,并将它的值赋为1

function unique(array = []) {
    const existingValues = {};
    const uniqueArray = [];
    
    for (let i = 0; i < array.length; i++) {
      if (existingValues[array[i]] === undefined) {
        existingValues[array[i]] = 1;
        uniqueArray.push(array[i]);
      }
    }
    
    return uniqueArray;
}

filter + indexOf

数组的indexOf()方法可以返回元素在数组中第一次出现的位置,在遍历的过程中,判断当前元素的位置是否和第一次出现的位置相等,如果不等,说明这个元素就是重复数据,然后利用filter过滤掉即可。

function unique(array = []) {
    return integers.filter(
      (value, index, array) => array.indexOf(value) === index
    );
}

其他

还有另外一种场景:数组的元素是对象,对象的属性值是重复的。我们可以根据键来过滤掉重复的数据。对象数组结构be like:

const array = [
    { place: "here", name: "x", other: "other stuff1" },
    { place: "there", name: "x", other: "other stuff2" },
    { place: "here", name: "y", other: "other stuff4" },
    { place: "here", name: "z", other: "other stuff5" },
];

filter + findIndex

这种方法和上面的filter配合indexOf方法异曲同工。

function unique(array = [], prop) {
    return array.filter((value, index, self) => { // self就是array对象
        // 内部遍历 对比两个对象属性值相等时的索引是否和当前对象在数组中的索引是否相等
        return self.findIndex((o) => o[prop] === value[prop]) === index;
    });
}

还是散列表

散列表真好用 😃

function unique(array = [], key) {
    const existingValues = {};
    const uniqueArray = [];
    
    for (let i = 0; i < array.length; i++) {
      if (existingValues[array[i][key]] === undefined) {
        existingValues[array[i][key]] = 1;
        uniqueArray.push(array[i]);
      }
    }
    
    return uniqueArray;
}

参考:

  • How to remove all duplicates from an array of objects
  • Remove duplicate values from JS Array