1.使用 js 中的 filter
和 indexOf
来进行数组去重
// 示例数组
let array = [1, 2, 3, 1, 2, 4, 5, 3];
// 使用 filter 和 indexOf 进行去重
let uniqueArray = array.filter((value, index, self) => {
// 返回第一次出现的索引位置,若当前索引与第一次出现的索引相同,则保留该元素
return self.indexOf(value) === index;
});
console.log(uniqueArray); // 输出去重后的数组 [1, 2, 3, 4, 5]
2.使用 Set 数据结构
let array = [1, 2, 3, 1, 2, 4, 5, 3];
let uniqueArray = [...new Set(array)];
console.log(uniqueArray); // 输出去重后的数组 [1, 2, 3, 4, 5]
3.reduce
let array = [1, 2, 3, 1, 2, 4, 5, 3];
let uniqueArray = array.reduce((acc, currentValue) => {
if (acc.indexOf(currentValue) === -1) { // 这里检查当前值在累加器(acc)中是否不存在
acc.push(currentValue); // 如果不存在,就将其添加到累加器中
}
return acc; // 返回更新后的累加器
}, []); // 初始时,累加器为空数组
console.log(uniqueArray); // 输出去重后的数组 [1, 2, 3, 4, 5]
4.map
- 首先创建了一个
Map
对象 map
。
- 然后通过
for...of
循环遍历输入的数组 array
。
- 对于每个元素
item
,检查 map
中是否已经存在该元素(通过 map.has(item)
)。如果不存在,就使用 map.set(item, true)
将其添加到 map
中。由于 Map
的键是唯一的,所以重复的元素不会被再次添加。
- 最后,使用
Array.from(map.keys())
将 map
的键提取出来并转换为一个新的数组 uniqueArray
,从而实现了数组的去重。
let array = [1, 2, 3, 1, 2, 4, 5, 3];
let map = new Map();
for (let item of array) { // 遍历数组中的每个元素
if (!map.has(item)) { // 如果 Map 中不存在当前元素
map.set(item, true); // 将当前元素作为键,值为 true 存入 Map 中,利用 Map 键的唯一性来实现去重
}
}
let uniqueArray = Array.from(map.keys()); // 将 Map 的键转换为数组