如下是三种方法从数组里去重,而且返回惟一的值。我最喜欢的方式是使用Set,由于它是最短最简单的。es6
const array = [5, 2, 4, 5, 3]; console.log([...new Set(array)]) console.log(array.filter((item, index) => array.indexOf(item) === index)) console.log(array.reduce((unique, item) => unique.includes(item) ? unique: [...unique, item], [])) // result: [5, 2, 4, 3]
使用Set数组
让我开始解释Set是什么吧:微信
Set是由es6引入的一种新的数据对象,因为Set只容许你存储惟一值,因此当传递进去一个数组的时候,它将会移除任何重复的值。函数
好啦,然咱们回到咱们的代码中来看下到底都发生了什么。实际上他进行了如下的操做:翻译
const array = [5, 2, 4, 5, 3]; const set = new Set(array) const newArr = [...set] console.log(newArr) // result: [5, 2, 4, 3]
使用Array.from()函数来吧Set转为数组code
另外呢,你也能够使用Array.from()来吧Set转为数组。对象
const array = [5, 2, 4, 5, 3]; const set = new Set(array) const newArr = Array.from(set) console.log(newArr) // result: [5, 2, 4, 3]
使用filter索引
为了理解这个选项,让咱们来看看这两个方法都作了什么:indexOf和filterrem
indexOf()get
indexOf()返回咱们从数组里找到的第一个元素的索引。
const array = [5, 2, 4, 5, 3]; console.log(array.indexOf(5)) // 0 console.log(array.indexOf(2)) // 1 console.log(array.indexOf(8)) // -1
filter
filter()函数会根据咱们提供的条件建立一个新的数组。换一种说法,若是元素经过而且返回true,它将会包含在过滤后的数组中,若是有元素失败而且返回false,那么他就不会包含在过滤后的数组中。
咱们逐步看看在每次循环数组的时候都发生了什么。
const array = [5, 2, 4, 5, 3]; array.filter((item, index) => { console.log(item, index, array.indexOf(item), array.indexOf(item) === index) return array.indexOf(item) === index }) //输出 // 5 0 0 true // 2 1 1 true // 4 2 2 true // 5 3 0 false // 3 4 4 true
上面输出的代码见注释。重复的元素再也不于indexOf相匹配,因此在这些状况下,它的结果将会是false而且将不会被包含进过滤后的值当中。
检索重复的值
咱们也能够在数组中利用filter()函数来检索重复的值。咱们只须要像这样简单的调整下代码:
const array = [5, 2, 4, 5, 3]; array.filter((item, index) => { console.log(item, index, array.indexOf(item), array.indexOf(item) !== index) return array.indexOf(item) !== index }) //输出 // 5 0 0 false // 2 1 1 false // 4 2 2 false // 5 3 0 true // 3 4 4 false
使用reduce()函数
reduce()函数用于减小数组的元素并根据你传递过去的reducer函数,把他们最终合并到一个最终的数组中,
在这种状况下,咱们的reducer()函数咱们最终的数组是否包含了这个元素,若是不包含,就吧他放进最终的数组中,反之则跳过这个元素,最后再返回咱们最终的元素。
reduce()函数理解起来老是有那么一点费劲,因此呢,我们如今看下他是怎么运行的。
const array = [5, 2, 4, 5, 3]; array.reduce((unique, item) => { console.log(item, unique, unique.includes(item), unique.includes(item) ? unique: [...unique, item]) return unique.includes(item) ? unique: [...unique, item] }, []) //输出 // 5 [] false [5] // 2 [5] false [5, 2] // 4 [5, 2] false [5, 2, 4] // 5 [5, 2, 4] true [5, 2, 4] // 3 [5, 2, 4] false [5, 2, 4, 3]
转载自:http://www.lht.ren/article/12/
欢迎关注本人微信公众号:干货技术
翻译自: