在JavaScript中,处理数组去重有多种方法。以下是一些常见的方法:
1. 使用Set
Set是ES6中引入的一种新的数据结构,类似于数组,但所有元素都是唯一的。利用Set可以非常简洁地去除数组中的重复项。
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
方法检查元素首次出现的位置,如果当前位置与首次出现的位置相同,则保留该元素。
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
方法可以累积数组中的值,结合indexOf
或者一个辅助的Object/Map来确定一个元素是否已经被添加到结果数组。
const array = [1, 2, 2, 3, 4, 4, 5];
const uniqueArray = array.reduce((acc, current) => {
if (acc.indexOf(current) === -1) {
acc.push(current);
}
return acc;
}, []);
console.log(uniqueArray); // 输出 [1, 2, 3, 4, 5]
4. 使用对象或Map
利用对象或Map作为辅助数据结构,存储已经出现过的元素。这种方法在处理大型数组或数组项为复杂类型时特别有效。
const array = [1, 2, 2, 3, 4, 4, 5];
const uniqueMap = new Map();
const uniqueArray = array.filter(item => !uniqueMap.has(item) && uniqueMap.set(item, true));
console.log(uniqueArray); // 输出 [1, 2, 3, 4, 5]
5. 使用forEach与includes
这是另一个结合数组方法的例子,使用forEach
来迭代数组,并通过includes
检查新数组中是否已经包含了当前元素。
const array = [1, 2, 2, 3, 4, 4, 5];
let uniqueArray = [];
array.forEach(item => {
if (!uniqueArray.includes(item)) {
uniqueArray.push(item);
}
});
console.log(uniqueArray); // 输出 [1, 2, 3, 4, 5]