JS数组去重常用4种重方法 | 您所在的位置:网站首页 › js数组方法练习 › JS数组去重常用4种重方法 |
使用Set数据结构结合(拓展运算符or Array.assign方法):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()方法:利用Array的filter()方法,遍历数组并返回满足条件的唯一元素。同时利用indexOf()方法检查当前元素在数组中的第一个索引位置和当前索引位置是否相同,如果不同,则表示该元素是重复的。 const array = [1, 2, 2, 3, 4, 4, 5]; const uniqueArray = array.filter((value, index, self) => { return self.indexOf(value) === index; }); console.log(uniqueArray); // [1, 2, 3, 4, 5]3.使用reduce()结合includes()方法:利用Array的reduce()方法,遍历数组并将唯一的元素累积到一个新数组中。利用includes()方法检查当前元素在数组中是否已经存在,如果不存在,则将其添加到结果数组中。 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]4.使用Map数据结构:利用Map数据结构的键唯一性,遍历数组,将数组的元素作为Map的键,并将对应键值设为1,然后将Map的键转换为数组。 const array = [1, 2, 2, 3, 4, 4, 5]; const uniqueArray = Array.from(new Map(array.map((value) => [value, 1])).keys()); console.log(uniqueArray); // [1, 2, 3, 4, 5] |
CopyRight 2018-2019 实验室设备网 版权所有 |