使用 Set
Set 是 ES6 引入的数据结构,它只允许存储唯一值,因此可以通过将数组转换为 Set 来实现去重。
const array = [1, 2, 3, 4, 3, 2, 1];
const uniqueArray = [...new Set(array)];
console.log(uniqueArray); // 输出: [1, 2, 3, 4]
使用 filter 和 indexOf
通过 filter 方法遍历数组并使用 indexOf 来检查元素的第一次出现位置,保留那些位置与当前索引相同的元素。
const array = [1, 2, 3, 4, 3, 2, 1];
const uniqueArray = array.filter((item, index) => array.indexOf(item) === index);
console.log(uniqueArray); // 输出: [1, 2, 3, 4]
使用 reduce 和 includes
使用 reduce 方法遍历数组并逐步构建一个不包含重复元素的新数组。
const array = [1, 2, 3, 4, 3, 2, 1];
const uniqueArray = array.reduce((accumulator, item) => {
if (!accumulator.includes(item)) {
accumulator.push(item);
}
return accumulator;
}, []);
console.log(uniqueArray); // 输出: [1, 2, 3, 4]
使用 forEach 和 includes
使用 forEach 方法遍历数组,同时构建一个新的数组,只有当元素不在新数组中时才将其添加进去。
const array = [1, 2, 3, 4, 3, 2, 1];
const uniqueArray = [];
array.forEach(item => {
if (!uniqueArray.includes(item)) {
uniqueArray.push(item);
}
});
console.log(uniqueArray); // 输出: [1, 2, 3, 4]
使用 Map
通过 Map 来记录元素的出现次数,从而构建一个不包含重复元素的数组。
const array = [1, 2, 3, 4, 3, 2, 1];
const uniqueArray = array.sort().reduce((acc, item) => {
if (acc.length === 0 || acc[acc.length - 1] !== item) {
acc.push(item);
}
return acc;
}, []);
console.log(uniqueArray); // 输出: [1, 2, 3, 4]
使用 sort 和 reduce
首先对数组进行排序,然后使用 reduce 方法遍历,过滤掉相邻的重复元素。
const array = [1, 2, 3, 4, 3, 2, 1];
const uniqueArray = array.sort().reduce((acc, item) => {
if (acc.length === 0 || acc[acc.length - 1] !== item) {
acc.push(item);
}
return acc;
}, []);
console.log(uniqueArray); // 输出: [1, 2, 3, 4]
以上就是数组去重的几种方法,欢迎大家评论补充