更新时间:2023-06-01 来源:黑马程序员 浏览量:
在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.使用Array.prototype.filter()方法:
可以使用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.使用Array.prototype.reduce()方法:
可以使用reduce()方法遍历数组,并将每个元素添加到结果数组中,但只有在结果数组中不存在相同的元素时才添加。
const array = [1, 2, 2, 3, 4, 4, 5];
const uniqueArray = array.reduce((acc, value) => {
if (!acc.includes(value)) {
acc.push(value);
}
return acc;
}, []);
console.log(uniqueArray); // [1, 2, 3, 4, 5]
4.使用for循环和临时对象:
使用for循环遍历数组,将数组中的元素作为对象的属性,只保留第一次出现的元素。
const array = [1, 2, 2, 3, 4, 4, 5];
const uniqueArray = [];
const tempObj = {};
for (let i = 0; i < array.length; i++) {
if (!tempObj[array[i]]) {
tempObj[array[i]] = true;
uniqueArray.push(array[i]);
}
}
console.log(uniqueArray); // [1, 2, 3, 4, 5]
以上就是常见的JS去重方法,根据具体情况选择适合的方法来实现数组去重。