如何利用es6去重

8次阅读

共计 2191 个字符,预计需要花费 6 分钟才能阅读完成。

以下是三种方法从数组里去重,并且返回唯一的值。我最喜欢的方式是使用 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]

转载自:http://www.lht.ren/article/12/
欢迎关注本人微信公众号:干货技术
翻译自:
https://medium.com/dailyjs/ho…

正文完
 0