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

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

从数组 JavaScript 中删除重复项

在 JavaScript 中,删除数组中的重复项是一项非常常见的任务。重复项可能会导致意外的行为或结果,并使您的代码执行更慢。以下是一些方法可以帮助您删除数组中的重复项。

使用 Set 对象

Set 对象是 ES6 中新增的一项特性,它是一组不重复的值的集合。您可以使用 Set 对象来删除数组中的重复项。

const array = [1, 2, 3, 3, 4, 5, 5, 6];
const uniqueArray = [...new Set(array)];
console.log(uniqueArray); // [1, 2, 3, 4, 5, 6]

在示例中,我们首先使用 Set 对象创建一个新的集合。然后,我们将旧数组的元素展开到一个新数组中。

使用 filter() 和 indexOf()

您可以使用 filter() 方法和 indexOf() 方法来删除数组中的重复项。

const array = [1, 2, 3, 3, 4, 5, 5, 6];
const uniqueArray = array.filter((value, index) => array.indexOf(value) === index);
console.log(uniqueArray); // [1, 2, 3, 4, 5, 6]

在示例中,我们使用 filter() 方法来遍历数组并过滤出所有重复项。我们使用 indexOf() 方法来确定元素已经存在于数组中。

使用 reduce() 和 includes()

您可以使用 reduce() 方法和 includes() 方法来删除数组中的重复项。

const array = [1, 2, 3, 3, 4, 5, 5, 6];
const uniqueArray = array.reduce((unique, item) => unique.includes(item) ? unique : [...unique, item], []);
console.log(uniqueArray); // [1, 2, 3, 4, 5, 6]

在示例中,我们使用 reduce() 方法来聚合一个数组。我们使用 includes() 方法来确定元素是否重复。如果已经存在,则返回已经聚合的数组,否则将它添加到已聚合的数组中。

这是一些从 JavaScript 中删除数组中的重复项的方法,您可以根据需要选择其中之一来使用。