数组去重常见的5种方法
- 使用
Set
- 使用
filter
和indexOf
- 使用
reduce
和includes
- 使用
forEach
和Object
- 使用
Map
总结(推荐方法)
1、使用Set
– 推荐
Set
是 ES6 引入的集合类型,类似于数组,但其成员都是唯一的。这使得 Set
成为数组去重的一个非常简洁和高效的工具。
实现步骤:
- 将数组转换为 Set,自动去除重复的值。
- 将 Set 再转换回数组。
代码示例:
let array = [1, 2, 3, 4, 4, 3, 2, 1];
let uniqueArray = [...new Set(array)];
console.log(uniqueArray); // [1, 2, 3, 4]
解析:
new Set(array)
:创建一个 Set,自动去除数组中的重复值。[...new Set(array)]
:使用扩展运算符 … 将 Set 再转换为数组。
2、使用 filter
和 indexOf
filter
是数组的方法,用于过滤数组元素。indexOf
是数组的方法,用于返回某个指定元素在数组中首次出现的位置。
实现步骤:
- 使用
filter
遍历数组。 - 在每次遍历时,用
indexOf
检查当前元素在数组中的第一次出现的位置。 - 如果当前元素的索引等于它第一次出现的位置,则保留该元素,否则过滤掉。
代码示例:
let array = [1, 2, 3, 4, 4, 3, 2, 1];
let uniqueArray = array.filter((item, index) => array.indexOf(item) === index);
console.log(uniqueArray); // [1, 2, 3, 4]
解析:
array.filter((item, index) => ...)
:遍历数组,对每个元素执行一次提供的函数。array.indexOf(item)
:查找当前元素在数组中第一次出现的位置。array.indexOf(item) === index
:如果当前元素在数组中第一次出现的位置等于当前索引,则保留该元素。
3、使用 reduce
和 includes
使用 reduce 方法和 includes 方法去重。
let array = [1, 2, 3, 4, 4, 3, 2, 1];
let uniqueArray = array.reduce((acc, item) => {
if (!acc.includes(item)) {
acc.push(item);
}
return acc;
}, []);
console.log(uniqueArray); // [1, 2, 3, 4]
4、使用 forEach
和 Object
使用 forEach 方法和对象的键值对去重。
let array = [1, 2, 3, 4, 4, 3, 2, 1];
let obj = {};
array.forEach(item => {
obj[item] = true;
});
let uniqueArray = Object.keys(obj).map(Number);
console.log(uniqueArray); // [1, 2, 3, 4]
5、使用 Map
使用 Map 数据结构来去重。
let array = [1, 2, 3, 4, 4, 3, 2, 1];
let map = new Map();
array.forEach(item => {
if (!map.has(item)) {
map.set(item, true);
}
});
let uniqueArray = [...map.keys()];
console.log(uniqueArray); // [1, 2, 3, 4]
总结(推荐方法)
Set
去重 简单、高效,适合大多数场景。filter
和indexOf
去重 更为灵活,可以添加额外的条件或逻辑,但相对较慢,因为每次 filter 迭代都要执行一次 indexOf 查找。
推荐使用 Set
进行数组去重,因为这种方法最简洁、性能较好,并且代码可读性高。其他方法在某些特定场景下也可能会有用,可以根据具体需求选择合适的方法。