JavaScript中数组去重的方法有哪些?哪个性能好?

42 阅读2分钟

"```markdown

JavaScript中数组去重的方法

1. 使用Set

Set是一种新的数据结构,可以自动去重。

const array = [1, 2, 2, 3, 4, 4, 5];
const uniqueArray = [...new Set(array)];
console.log(uniqueArray); // [1, 2, 3, 4, 5]

性能:时间复杂度为O(n),空间复杂度为O(n)。

2. 使用filter和indexOf

通过filter方法结合indexOf进行去重。

const array = [1, 2, 2, 3, 4, 4, 5];
const uniqueArray = array.filter((item, index) => array.indexOf(item) === index);
console.log(uniqueArray); // [1, 2, 3, 4, 5]

性能:时间复杂度为O(n^2),空间复杂度为O(n)。

3. 使用reduce和includes

结合reduceincludes实现去重。

const array = [1, 2, 2, 3, 4, 4, 5];
const uniqueArray = array.reduce((acc, item) => {
    if (!acc.includes(item)) {
        acc.push(item);
    }
    return acc;
}, []);
console.log(uniqueArray); // [1, 2, 3, 4, 5]

性能:时间复杂度为O(n^2),空间复杂度为O(n)。

4. 使用排序

先对数组排序,然后判断相邻元素去重。

const array = [1, 2, 2, 3, 4, 4, 5];
const uniqueArray = array.sort().filter((item, index, arr) => {
    return !index || item !== arr[index - 1];
});
console.log(uniqueArray); // [1, 2, 3, 4, 5]

性能:时间复杂度为O(n log n),空间复杂度为O(n)。

5. 使用对象键

利用对象的键唯一性进行去重。

const array = [1, 2, 2, 3, 4, 4, 5];
const uniqueArray = Object.keys(array.reduce((acc, item) => {
    acc[item] = true; // 将数组值作为对象的键
    return acc;
}, {})).map(Number);
console.log(uniqueArray); // [1, 2, 3, 4, 5]

性能:时间复杂度为O(n),空间复杂度为O(n)。

6. 使用Map

使用Map结构进行去重。

const array = [1, 2, 2, 3, 4, 4, 5];
const uniqueArray = Array.from(new Map(array.map(item => [item, item])).values());
console.log(uniqueArray); // [1, 2, 3, 4, 5]

性能:时间复杂度为O(n),空间复杂度为O(n)。

性能比较

  • SetMap方法在大多数情况下性能较好,时间复杂度为O(n)。
  • filter结合indexOfreduce的方法性能较差,时间复杂度为O(n^2)。
  • 排序去重的性能受限于排序算法,一般为O(n log n)。

在实际开发中,推荐使用SetMap方法进行数组去重,因其简洁且性能优越。