首先需要明确一下,去除数组内重复的数据有两种情况:

  1. 数组内元素是基本数据类型(如数字、字符串等)
  2. 数组内元素是对象类型

针对第一种情况,可以使用ES6中的Set对象来去重,然后再转换成数组。代码如下:

const arr = [1, 2, 3, 2, 4, 3];

// 使用Set对象去重
const set = new Set(arr);

// 将Set对象转换成数组
const newArr = Array.from(set);

console.log(newArr); // [1, 2, 3, 4]

针对第二种情况,需要遍历数组,比较每个元素的属性值来判断是否重复。我们可以定义一个函数来判断两个对象是否相等,然后使用filter()方法来过滤掉重复的元素。代码如下:

const arr = [
  {id: 1, name: 'Alice'},
  {id: 2, name: 'Bob'},
  {id: 1, name: 'Alice'},
  {id: 3, name: 'Charlie'},
];

// 判断两个对象是否相等
function isEqual(obj1, obj2) {
  return obj1.id === obj2.id && obj1.name === obj2.name;
}

// 使用filter()方法过滤掉重复元素
const newArr = arr.filter((item, index) => {
  return arr.findIndex(obj => isEqual(item, obj)) === index;
});

console.log(newArr); // [{id: 1, name: 'Alice'}, {id: 2, name: 'Bob'}, {id: 3, name: 'Charlie'}]

需要注意的是,如果对象的属性值是引用类型的话,需要对这些属性值进行比较。比如:

const arr = [
  {id: 1, name: 'Alice', friends: ['Bob', 'Charlie']},
  {id: 2, name: 'Bob', friends: ['Alice']},
  {id: 1, name: 'Alice', friends: ['Bob', 'Charlie']},
  {id: 3, name: 'Charlie', friends: []},
];

// 判断两个对象是否相等
function isEqual(obj1, obj2) {
  if (obj1.id !== obj2.id || obj1.name !== obj2.name) {
    return false;
  }
  if (obj1.friends.length !== obj2.friends.length) {
    return false;
  }
  for (let i = 0; i < obj1.friends.length; i++) {
    if (obj1.friends[i] !== obj2.friends[i]) {
      return false;
    }
  }
  return true;
}

// 使用filter()方法过滤掉重复元素
const newArr = arr.filter((item, index) => {
  return arr.findIndex(obj => isEqual(item, obj)) === index;
});

console.log(newArr); // [{id: 1, name: 'Alice', friends: ['Bob', 'Charlie']}, {id: 2, name: 'Bob', friends: ['Alice']}, {id: 3, name: 'Charlie', friends: []}]

至于如何注释,可以在代码中添加注释来解释每个步骤的作用,比如:

// 去除数组内重复的数字并注释

const arr = [1, 2, 3, 2, 4, 3];

// 使用Set对象去重
const set = new Set(arr);

// 将Set对象转换成数组
const newArr = Array.from(set);

console.log(newArr); // [1, 2, 3, 4]


// 去除数组内重复的对象并注释

const arr = [
  {id: 1, name: 'Alice'},
  {id: 2, name: 'Bob'},
  {id: 1, name: 'Alice'},
  {id: 3, name: 'Charlie'},
];

// 判断两个对象是否相等
function isEqual(obj1, obj2) {
  return obj1.id === obj2.id && obj1.name === obj2.name;
}

// 使用filter()方法过滤掉重复元素
const newArr = arr.filter((item, index) => {
  return arr.findIndex(obj => isEqual(item, obj)) === index;
});

console.log(newArr); // [{id: 1, name: 'Alice'}, {id: 2, name: 'Bob'}, {id: 3, name: 'Charlie'}]
js思考如何去除数组内重复的数据并注释

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

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