在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 和 indexOf
filter 方法结合 indexOf 可以实现数组去重。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]
优点: 对所有类型的数据都有效。
缺点: 性能较低,因为 indexOf 需要在数组中遍历查找元素。
3. 使用 reduce 方法
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]
优点: 可以灵活处理各种去重逻辑。
缺点: 相对复杂,性能不如 Set。
4. 使用 Map 对象
Map 对象保存键值对,键是唯一的。可以通过使用 Map 来实现数组去重,尤其在对象数组去重时非常有用。
const array = [{ id: 1 }, { id: 2 }, { id: 1 }, { id: 3 }];
const uniqueArray = [...new Map(array.map(item => [item.id, item])).values()];
console.log(uniqueArray); // [{ id: 1 }, { id: 2 }, { id: 3 }]
优点: 对对象数组的去重很有效。
缺点: 代码稍微复杂一点,需要对 Map 和 values() 有一定了解。
5. 使用 forEach 和 Object
可以用 forEach 遍历数组,通过对象的键值对存储元素来实现去重。这种方法也适用于对象数组的去重。
const array = [1, 2, 2, 3, 4, 4, 5];
const seen = {};
const uniqueArray = [];
array.forEach(item => {if (!seen[item]) {seen[item] = true;uniqueArray.push(item);}
});
console.log(uniqueArray); // [1, 2, 3, 4, 5]
优点: 灵活,易于理解和使用。
缺点: 需要手动管理键值对,稍显冗长。
总结
- 最简单、常用的方法:使用
Set,适合大多数去重需求。 - 复杂数据结构(如对象数组):使用
Map更灵活有效。 - 兼容性和性能:
filter和reduce方法在处理复杂逻辑时更加灵活,但性能不如Set。