📌  相关文章
📜  如何删除数组javascript中的重复对象(1)

📅  最后修改于: 2023-12-03 15:08:29.861000             🧑  作者: Mango

如何删除数组JavaScript中的重复对象

在JavaScript中,处理数组中的重复对象是一个常见的任务。在本文中,我们将讨论如何使用不同的方法删除JavaScript数组中的重复对象。

方法一:使用Set对象

Set对象是一种可以存储唯一键的对象。可以使用Set对象来删除一个数组中的重复对象。以下是示例代码:

const arr = [{id: 1, name: 'John'}, {id: 2, name: 'Jane'}, {id: 1, name: 'John'}];
const uniqueArr = Array.from(new Set(arr.map(JSON.stringify))).map(JSON.parse);
console.log(uniqueArr);

以上代码首先将数组中的每个对象转换为字符串形式,然后将字符串数组传递给Set对象。最后,将Set对象转换回包含原始对象的数组。

方法二:使用filter方法

数组的filter()方法可以用于过滤出不同的对象。以下是示例代码:

const arr = [{id: 1, name: 'John'}, {id: 2, name: 'Jane'}, {id: 1, name: 'John'}];
const uniqueArr = arr.filter((obj, index, self) => self.findIndex((o) => o.id === obj.id && o.name === obj.name) === index);
console.log(uniqueArr);

以上代码使用了filter()方法以及findIndex()方法。findIndex()方法返回数组中第一个满足指定条件的元素的索引。filter()方法则返回一个新的包含符合条件的元素的数组。

方法三:使用reduce方法

reduce()方法用于将数组中的元素通过一个函数进行累加。以下是示例代码:

const arr = [{id: 1, name: 'John'}, {id: 2, name: 'Jane'}, {id: 1, name: 'John'}];
const uniqueArr = arr.reduce((acc, cur) => {
  const index = acc.findIndex((obj) => obj.id === cur.id && obj.name === cur.name);
  if (index < 0) {
    acc.push(cur);
  } else {
    acc[index] = cur;
  }
  return acc;
}, []);
console.log(uniqueArr);

以上代码使用reduce()方法和findIndex()方法来判断数组中是否已存在当前对象。如果不存在,则将当前对象添加到累加器(acc)中。如果存在,则将当前对象替换原来的对象。

结论

这三种方法可以删掉JavaScript数组中的重复对象。如果您需要在您的项目中使用这些方法,请仔细评估并测试这些方法的性能和稳定性。