面试官 🤔:JS 如何实现去重……

81 阅读1分钟

Screen Recording 2024-07-13 at 23.26.27.gif

在 JavaScript 中,可以通过多种方式来实现数组去重。以下是一些常见的方法:

1. 使用 Set

Set 是 ES6 引入的一种数据结构,它可以自动移除重复项

参考:developer.mozilla.org/zh-CN/docs/…

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

2. 使用 filterindexOf

可以使用 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]

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. 使用 forEachincludes

通过 forEach 循环和 includes 方法来实现去重

参考: developer.mozilla.org/zh-CN/docs/…

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

以上这些方法都可以实现数组去重