如何利用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只允许你存储唯一值,所以当传递进去一个数组的时候,它将会移除任何重复的值。

好啦,然我们回到我们的代码中来看下到底都发生了什么。实际上他进行了以下的操作:

  1. 首先,我们创建了新的Set并且把数组当作入参传递了进去,由于Set仅仅允许唯一值,所以所有重复值将会被移除。

  2. 现在重复值已经消失了,我们将会利用…把它重新转为数组。

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]

翻译自:

https://medium.com/dailyjs/how-to-remove-array-duplicates-in-es6-5daa8789641c

转载自:http://www.lht.ren/article/12/

欢迎关注本人微信公众号:干货技术

猜你喜欢

转载自blog.csdn.net/qq_15697653/article/details/86497430