來(lái)一個(gè)老生常談的話題,JavaScript中,數(shù)組如何去重?
關(guān)于如何去除一個(gè)給定數(shù)組中的重復(fù)項(xiàng),應(yīng)該是 Javascript 面試中最常見的一個(gè)問(wèn)題了,最常見的方式有三種:Set、Array.prototype.filter 以及 Array.prototype.reduce,對(duì)于只有簡(jiǎn)單數(shù)據(jù)的數(shù)組來(lái)講,我最喜歡 Set,沒別的,就是寫起來(lái)簡(jiǎn)單。
- 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
先讓我們來(lái)看看 Set 到底是個(gè)啥
- Set 對(duì)象允許你存儲(chǔ)任何類型的唯一值,無(wú)論是原始值或者是對(duì)象引用。
- <cite>https://developer.mozilla.org...</cite>
- 首先,Set 中只允許出現(xiàn)唯一值
- 唯一性是比對(duì)原始值或者對(duì)象引用
const bySet = [...new Set(originalArray)] 這一段的操作,我們將它拆分來(lái)看:
- 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 轉(zhuǎn)為 Array 時(shí),也可以使用 Array.from(set)。
使用 Array.prototype.filter
要理解 filter 方法為什么可以去重,需要關(guān)注一下另一個(gè)方法 indexOf
- indexOf()方法返回在數(shù)組中可以找到一個(gè)給定元素的第一個(gè)索引,如果不存在,則返回 -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() 方法創(chuàng)建一個(gè)新數(shù)組, 其包含通過(guò)所提供函數(shù)實(shí)現(xiàn)的測(cè)試的所有元素。
- <cite>https://developer.mozilla.org...</cite>
filter 方法接受兩個(gè)參數(shù):
- 第一個(gè)參數(shù):一個(gè)回調(diào)函數(shù), filter 會(huì)將數(shù)據(jù)中的每一項(xiàng)都傳遞給該函數(shù),若該函數(shù)返回 真值,則數(shù)據(jù)保存,返回 假值,則數(shù)據(jù)將不會(huì)出現(xiàn)在新生成的數(shù)據(jù)中
- 第二個(gè)參數(shù):回調(diào)函數(shù)中 this 的指向
我們將上面的去重方法按下面這樣重寫一下,就可以看清整個(gè) filter 的執(zhí)行過(guò)程了。
- const originalArray = [1, 2, '咩', 1, 'Super Ball', '咩', '咩', 'Super Ball', 4]
- const table = []
- const byFilter = originalArray.filter((item, index) => {
- // 如果找到的索引與當(dāng)前索引一致,則保留該值
- const shouldKeep = originalArray.indexOf(item) === index
- table.push({
- 序號(hào): index,
- 值: item,
- 是否應(yīng)該保留: shouldKeep ? '保留' : '刪除'
- })
- return shouldKeep
- })
- console.log(byFilter)
- console.table(table)
使用 Array.prototype.reduce
- reduce() 方法對(duì)數(shù)組中的每個(gè)元素執(zhí)行一個(gè)由您提供的 reducer 函數(shù)(升序執(zhí)行),將其結(jié)果匯總為單個(gè)返回值。
- <cite>https://developer.mozilla.org...</cite>
Array.prototype.reduce 方法接受兩個(gè)參數(shù):
- Callback:回調(diào)函數(shù),它可以接收四個(gè)參數(shù)
- Accumulator:累計(jì)器,這個(gè)其實(shí)是讓很多人忽略的一點(diǎn),就是,累計(jì)器其實(shí)可以是任何類型的數(shù)據(jù)
- Current Value:當(dāng)前值
- Current Index:當(dāng)前值的索引
- Source Array:源數(shù)組
- Initial Value:累計(jì)器的初始值,就跟累計(jì)器一樣,這個(gè)參數(shù)也總是被絕大多數(shù)人忽略
就像 filter 章節(jié)一樣,我們來(lái)看看 reduce 的執(zhí)行過(guò)程:
- const originalArray = [1, 2, '咩', 1, 'Super Ball', '咩', '咩', 'Super Ball', 4]
- const byReduce = originalArray.reduce((unique, item, index, source) => {
- const exist = unique.includes(item)
- const next = unique.includes(item) ? unique : [...unique, item]
- console.group(`遍歷第 ${index} 個(gè)值`)
- console.log('當(dāng)前累計(jì)器:', unique)
- console.log('當(dāng)前值:', item)
- console.log('是否已添加進(jìn)累計(jì)器?', exist)
- console.log('新值', next)
- console.groupEnd()
- return next
- }, [])