📌  相关文章
📜  从数组 javascript 中删除重复项(1)

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

从数组 JavaScript 中删除重复项

在 JavaScript 中,有时我们需要从数组中删除重复的元素。这可以通过使用一些简单的技巧来实现。以下是一些方法:

使用 Set 对象

Set 对象是 ES6 中引入的一种新的数据结构,它允许你存储任何类型的唯一值。你可以使用 Set 对象来删除重复的元素。

const arr = [1, 2, 2, 3, 4, 4, 5];
const uniqueArr = Array.from(new Set(arr));
console.log(uniqueArr); // [1, 2, 3, 4, 5]

上面的代码创建了一个 Set 对象,从数组中删除了所有重复的元素,并将 Set 对象转换回数组。

使用 filter() 方法

filter() 方法允许你过滤数组中的元素。你可以使用它来删除重复的元素。在 filter() 方法中,你可以使用 indexOf() 方法来检查元素是否已经存在于数组中。

const arr = [1, 2, 2, 3, 4, 4, 5];
const uniqueArr = arr.filter((item, index) => arr.indexOf(item) === index);
console.log(uniqueArr); // [1, 2, 3, 4, 5]

这里的 filter() 方法将数组中每个元素传递给回调函数,如果该元素的索引与 indexOf() 方法返回的索引相同,则该元素被保留。因此,只有唯一的元素被保留下来。

使用 reduce() 方法

reduce() 方法允许你将数组的所有元素合并为单个值。你可以使用它来删除重复的元素。在 reduce() 方法中,你可以使用 includes() 方法来检查元素是否已经存在于数组中。

const arr = [1, 2, 2, 3, 4, 4, 5];
const uniqueArr = arr.reduce((accumulator, currentValue) => {
  if (!accumulator.includes(currentValue)) {
    accumulator.push(currentValue);
  }
  return accumulator;
}, []);
console.log(uniqueArr); // [1, 2, 3, 4, 5]

这里的 reduce() 方法将数组中的每个元素传递给回调函数,以便将它们合并为一个数组。如果 accumulator 数组不包含当前值,则它会被添加到 accumulator 中。最终,accumulator 数组将包含所有唯一的元素。

使用 ES6 中的 Map 对象

Map 对象是一个键值对的集合,它允许你存储任何类型的值。你可以使用 Map 对象来删除重复的元素。在 Map 对象中,重复的元素将被覆盖。

const arr = [1, 2, 2, 3, 4, 4, 5];
const uniqueArr = Array.from(new Map(arr.map((item) => [item, item])).values());
console.log(uniqueArr); // [1, 2, 3, 4, 5]

上面的代码首先将数组转换为 Map 对象,其中键和值均为数组中的每个元素。然后,通过使用 Array.from() 方法和 Map 对象中的 values() 方法,将 Map 对象转换回数组。因为 Map 对象中的键是唯一的,所有重复的元素都将被删除。