更新时间: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去重方法,根据具体情况选择适合的方法来实现数组去重。
1024首播|39岁程序员逆袭记:不被年龄定义,AI浪潮里再迎春天
2025-10-241024程序员节丨10年同行,致敬用代码改变世界的你
2025-10-24【AI设计】北京143期毕业仅36天,全员拿下高薪offer!黑马AI设计连续6期100%高薪就业
2025-09-19【跨境电商运营】深圳跨境电商运营毕业22个工作日,就业率91%+,最高薪资达13500元
2025-09-19【AI运维】郑州运维1期就业班,毕业14个工作日,班级93%同学已拿到Offer, 一线均薪资 1W+
2025-09-19【AI鸿蒙开发】上海校区AI鸿蒙开发4期5期,距离毕业21天,就业率91%,平均薪资14046元
2025-09-19