js 数组去重
2020-12-13 06:22
标签:唯一值 number 来源 nbsp rip w3c js 数组 func 创建 来源:https://www.w3cplus.com/javascript/javascript-tips.html ES6提供了几种简洁的数组去重的方法,但该方法并不适合处理非基本类型的数组。对于基本类型的数组去重,可以使用 这是ES6中的新特性,在ES6之前,要实现同样的效果,我们需要使用更多的代码。该技巧适用于包含基本类型的数组: 除了上面的方法之外,还可以使用 另外,还可以使用 注意, js 数组去重 标签:唯一值 number 来源 nbsp rip w3c js 数组 func 创建 原文地址:https://www.cnblogs.com/arealy/p/11175719.html1、数组去重
... new Set()
来过滤掉数组中重复的值,创建一个只有唯一值的新数组。const array = [1, 1, 2, 3, 5, 5, 1]
const uniqueArray = [...new Set(array)];
console.log(uniqueArray);
> Result:(4) [1, 2, 3, 5]
undefined
、null
、boolean
、string
和number
。如果数组中包含了一个object
,function
或其他数组,那就需要使用另一种方法。Array.from(new Set())
来实现:const array = [1, 1, 2, 3, 5, 5, 1]
Array.from(new Set(array))
> Result:(4) [1, 2, 3, 5]
Array
的.filter
及 indexOf()
来实现const array = [1, 1, 2, 3, 5, 5, 1]
array.filter((arr, index) => array.indexOf(arr) === index)
> Result:(4) [1, 2, 3, 5]
indexOf()
方法将返回数组中第一个出现的数组项。这就是为什么我们可以在每次迭代中将indexOf()
方法返回的索引与当索索引进行比较,以确定当前项是否重复。
下一篇:做JAVA的需要了解的框架