副问题[/!--empirenews.page--]

关于怎样去除一个给定命组中的一再项,应该是 Javascript 口试中最常见的一个题目了,最常见的方法有三种:Set、Array.prototype.filter 以及 Array.prototype.reduce,对付只有简朴数据的数组来讲,我最喜好 Set,没此外,就是写起来简朴。
- const originalArray = [1, 2, '咩', 1, 'Super Ball', '咩', '咩', 'Super Ball', 4]
- const bySet = [...new Set(originalArray)]
- const byFilter = originalArray.filter((item, index) => originalArray.indexOf(item) === index)
- const byReduce = originalArray.reduce((unique, item) => unique.includes(item) ? unique : [...unique, item], [])
行使 Set
先让我们来看看 Set 到底是个啥
- Set 工具应承你存储任何范例的独一值,无论是原始值可能是工具引用。
- <cite>https://developer.mozilla.org...</cite>
- 起首,Set 中只应承呈现独一值
- 独一性是比对原始值可能工具引用
const bySet = [...new Set(originalArray)] 这一段的操纵,我们将它拆分来看:
- const originalArray = [1, 2, '咩', 1, 'Super Ball', '咩', '咩', 'Super Ball', 4]
- const uniqueSet = new Set(originalArray)
- // 获得 Set(5) [ 1, 2, "咩", "Super Ball", 4 ]
- const bySet = [...uniqueSet]
- // 获得 Array(5) [ 1, 2, "咩", "Super Ball", 4 ]
在将 Set 转为 Array 时,也可以行使 Array.from(set)。
行使 Array.prototype.filter
要领略 filter 要领为什么可以去重,必要存眷一下另一个要领 indexOf
- indexOf()要领返回在数组中可以找到一个给定元素的第一个索引,假如不存在,则返回 -1。
- <cite>https://developer.mozilla.org...</cite>
- const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];
- console.log(beasts.indexOf('bison'));
- // expected output: 1
- // start from index 2
- console.log(beasts.indexOf('bison', 2));
- // expected output: 4
- console.log(beasts.indexOf('giraffe'));
- // expected output: -1
- filter() 要领建设一个新数组, 其包括通过所提供函数实现的测试的全部元素。
- <cite>https://developer.mozilla.org...</cite>
filter 要领接管两个参数:
- 第一个参数:一个回调函数, filter 会将数据中的每一项都转达给该函数,若该函数返回 真值,则数据生涯,返回 假值,则数据将不会呈此刻新天生的数据中
- 第二个参数:回调函数中 this 的指向
我们将上面的去重要领按下面这样重写一下,就可以看清整个 filter 的执行进程了。
- const originalArray = [1, 2, '咩', 1, 'Super Ball', '咩', '咩', 'Super Ball', 4]
- const table = []
- const byFilter = originalArray.filter((item, index) => {
- // 假如找到的索引与当前索引同等,则保存该值
- const shouldKeep = originalArray.indexOf(item) === index
- table.push({
- 序号: index,
- 值: item,
- 是否应该保存: shouldKeep ? '保存' : '删除'
- })
- return shouldKeep
- })
- console.log(byFilter)
- console.table(table)

行使 Array.prototype.reduce
- reduce() 要领对数组中的每个元素执行一个由您提供的 reducer 函数(升序执行),将其功效汇总为单个返回值。
- <cite>https://developer.mozilla.org...</cite>
(编辑:湖南网)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|