有多种方法可以对数组进行去重:

  1. 使用Set数据结构:将数组元素添加到Set中,Set会自动去除重复的元素,然后再将Set转换为数组。
const array = [1, 2, 2, 3, 4, 4];
const uniqueArray = [...new Set(array)];
console.log(uniqueArray); // [1, 2, 3, 4]
  1. 使用filter方法:使用filter方法对数组进行遍历,只保留第一次出现的元素。
const array = [1, 2, 2, 3, 4, 4];
const uniqueArray = array.filter((item, index) => array.indexOf(item) === index);
console.log(uniqueArray); // [1, 2, 3, 4]
  1. 使用reduce方法:使用reduce方法对数组进行遍历,将元素添加到一个新数组中,如果新数组中已经存在该元素,则跳过。
const array = [1, 2, 2, 3, 4, 4];
const uniqueArray = array.reduce((acc, item) => {
  if (!acc.includes(item)) {
    acc.push(item);
  }
  return acc;
}, []);
console.log(uniqueArray); // [1, 2, 3, 4]
  1. 使用for循环:使用for循环遍历数组,将元素添加到一个新数组中,如果新数组中已经存在该元素,则跳过。
const array = [1, 2, 2, 3, 4, 4];
const uniqueArray = [];
for (let i = 0; i < array.length; i++) {
  if (!uniqueArray.includes(array[i])) {
    uniqueArray.push(array[i]);
  }
}
console.log(uniqueArray); // [1, 2, 3, 4]
数组去重方法

原文地址: https://www.cveoy.top/t/topic/jgGw 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录