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

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

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

在使用 JavaScript 进行开发时,我们经常会遇到需要对数组对象进行去重的场景。本文将介绍如何在 JavaScript 中删除重复的数组对象。

方法一:使用 Set

使用 Set 是最简单的方法之一,Set 会自动去重,将数组元素转换成 Set 后,再将其转换回数组即可。

const arr = [
  { id: 1, name: 'John' },
  { id: 2, name: 'Emily' },
  { id: 3, name: 'John' },
  { id: 2, name: 'Emily' }
];

const result = Array.from(new Set(arr.map(JSON.stringify)), JSON.parse);

console.log(result); // [ { id: 1, name: 'John' }, { id: 2, name: 'Emily' }, { id: 3, name: 'John' } ]

在这个代码片段中,我们首先使用 map 方法将数组元素转换成 JSON 字符串,然后使用 Set 进行去重,将结果转换成数组后使用 JSON.parse 方法将其转换成数组对象。

方法二:使用 reduce

使用 reduce 方法也可以对数组对象进行去重操作。

const arr = [
  { id: 1, name: 'John' },
  { id: 2, name: 'Emily' },
  { id: 3, name: 'John' },
  { id: 2, name: 'Emily' }
];

const result = arr.reduce((unique, current) => {
  if (!unique.some(item => item.id === current.id)) {
    unique.push(current);
  }
  return unique;
}, []);

console.log(result); // [ { id: 1, name: 'John' }, { id: 2, name: 'Emily' }, { id: 3, name: 'John' } ]

在这个代码片段中,我们使用 reduce 方法遍历数组元素,使用 some 方法判断数组中是否存在相同的对象,如果不存在则将其添加到一个新的数组中,最终返回去重后的数组。

方法三:使用 filter

使用 filter 方法也可以对数组对象进行去重操作。

const arr = [
  { id: 1, name: 'John' },
  { id: 2, name: 'Emily' },
  { id: 3, name: 'John' },
  { id: 2, name: 'Emily' }
];

const result = arr.filter((item, index, arr) => {
  return arr.findIndex(t => t.id === item.id) === index;
});

console.log(result); // [ { id: 1, name: 'John' }, { id: 2, name: 'Emily' }, { id: 3, name: 'John' } ]

在这个代码片段中,我们使用 filter 方法遍历数组元素,使用 findIndex 方法查找数组中是否存在相同的对象,如果不存在则返回 true,最终返回去重后的数组。

总之,以上三种方法都可以在 JavaScript 中对数组对象进行去重操作,具体使用哪种方法取决于开发者的个人喜好和项目需求。