怎样使用es6实现去重(代码示例)
以下是三种办法从数组里去重,并且返回独一的值。我最喜爱的方式是使用Set,由于它是最短最简便的。
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只同意你储备独一值,所以当传递进去一个数组的时候,它将会移除任何反复的值。
好啦,然我们回到我们的代码中来看下到底都发生了什么。实际上他停止了以下的操纵:
第一,我们创立了新的Set并且把数组当作入参传递了进去,由于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转为数组
别的呢,你也可以使用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和filter
indexOf()
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]
以上就是怎样使用es6实现去重(代码示例)的具体内容,更多请关注百分百源码网其它相关文章!