告别重复数据:探索JavaScript数组去重的艺术

635 阅读2分钟

在 JavaScript 中,有多种方法可以实现数组去重,这些方法可以根据您的需求和偏好进行选择。以下是一些常见的数组去重方法的详细介绍:

1. 使用 Set 数据结构

Set 是 ES6 引入的数据结构,它存储唯一值,因此可以用于数组去重。

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

这种方法的优点是简单、高效,同时保持了原始数组的顺序。

2. 使用 filter 方法

使用 filter 方法和 indexOf 来过滤重复的元素。

const array = [1, 2, 2, 3, 4, 4, 5];
const uniqueArray = array.filter((value, index, self) => self.indexOf(value) === index);
console.log(uniqueArray); // 输出: [1, 2, 3, 4, 5]

这种方法较为通用,但在大型数组上性能可能较差。

3. 使用 reduce 方法

使用 reduce 方法和一个辅助数组来构建去重后的新数组。

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

这种方法具有较好的通用性和可读性。

4. 使用 Map 数据结构

使用 Map 数据结构,其中键是数组中的唯一值。

const array = [1, 2, 2, 3, 4, 4, 5];
const map = new Map();
const uniqueArray = [];
for (const item of array) {
  if (!map.has(item)) {
    map.set(item, true);
    uniqueArray.push(item);
  }
}
console.log(uniqueArray); // 输出: [1, 2, 3, 4, 5]

这种方法具有较好的性能,并保持了原始数组的顺序。

5. 使用递归方法

递归方法适用于多维数组的去重。

function uniqueArray(array) {
  return array.filter((value, index, self) => {
    if (Array.isArray(value)) {
      return uniqueArray(value); // 递归处理多维数组
    }
    return self.indexOf(value) === index;
  });
}

const nestedArray = [1, 2, [2, 3], [4, 4], 5];
const result = uniqueArray(nestedArray);
console.log(result); // 输出: [1, 2, [3], [4], 5]

这种方法适用于处理嵌套数组。

6. 使用 ES6 的 reduce 和 includes

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

这种方法简单明了,但在大型数组上性能可能较差。

7. 使用 ES6 的 filter 和 indexOf

const array = [1, 2, 2, 3, 4, 4, 5];
const uniqueArray = array.filter((value, index, self) => self.indexOf(value) === index);
console.log(uniqueArray); // 输出: [1, 2, 3, 4, 5]

这种方法具有较好的通用性,但在大型数组上性能可能较差。

您可以根据项目需求和性能要求选择合适的方法。使用 SetMap 是性能最佳的方式,但其他方法也可以在大多数情况下正常工作。