百分百源码网-让建站变得如此简单! 登录 注册 签到领金币!

主页 | 如何升级VIP | TAG标签

当前位置: 主页>网站教程>JS教程> 怎样使用es6实现去重(代码示例)
分享文章到:

怎样使用es6实现去重(代码示例)

发布时间:09/01 来源:未知 浏览: 关键词:
本篇文章给大家带来的内容是关于怎样使用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]

以上就是怎样使用es6实现去重(代码示例)的具体内容,更多请关注百分百源码网其它相关文章!

打赏

打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

百分百源码网 建议打赏1~10元,土豪随意,感谢您的阅读!

共有150人阅读,期待你的评论!发表评论
昵称: 网址: 验证码: 点击我更换图片
最新评论

本文标签

广告赞助

能出一分力是一分吧!

订阅获得更多模板

本文标签

广告赞助

订阅获得更多模板