代碼寫(xiě)得好,Reduce少不了,我用它在同事面前秀了一波!
數(shù)組中的 reduce 猶如一只魔法棒,通過(guò)它可以做一些黑科技一樣的事情。語(yǔ)法如下:
- reduce(callback(accumulator, currentValue[, index, array])[,initialValue])
reduce 接受兩個(gè)參數(shù),回調(diào)函數(shù)和初識(shí)值,初始值是可選的。回調(diào)函數(shù)接受4個(gè)參數(shù):積累值、當(dāng)前值、當(dāng)前下標(biāo)、當(dāng)前數(shù)組。
如果 reduce的參數(shù)只有一個(gè),那么積累值一開(kāi)始是數(shù)組中第一個(gè)值,如果reduce的參數(shù)有兩個(gè),那么積累值一開(kāi)始是出入的 initialValue 初始值。然后在每一次迭代時(shí),返回的值作為下一次迭代的 accumulator 積累值。
今天的這些例子的大多數(shù)可能不是問(wèn)題的理想解決方案,主要的目的是想說(shuō)介紹如何使用reduce來(lái)解決問(wèn)題。
求和和乘法
- // 求和
- [3, 5, 4, 3, 6, 2, 3, 4].reduce((a, i) => a + i);
- // 30
- // 有初始化值
- [3, 5, 4, 3, 6, 2, 3, 4].reduce((a, i) => a + i, 5 );
- // 35
- // 如果看不懂第一個(gè)的代碼,那么下面的代碼與它等價(jià)
- [3, 5, 4, 3, 6, 2, 3, 4].reduce(function(a, i){return (a + i)}, 0 );
- // 乘法
- [3, 5, 4, 3, 6, 2, 3, 4].reduce((a, i) => a * i);
查找數(shù)組中的最大值
如果要使用 reduce 查找數(shù)組中的最大值,可以這么做:
- [3, 5, 4, 3, 6, 2, 3, 4].reduce((a, i) => Math.max(a, i), -Infinity);
上面,在每一次迭代中,我們返回累加器和當(dāng)前項(xiàng)之間的最大值,最后我們得到整個(gè)數(shù)組的最大值。
如果你真想在數(shù)組中找到最大值,不要有上面這個(gè),用下面這個(gè)更簡(jiǎn)潔:
- Math.max(...[3, 5, 4, 3, 6, 2, 3, 4]);
連接不均勻數(shù)組
- let data = [
- ["The","red", "horse"],
- ["Plane","over","the","ocean"],
- ["Chocolate","ice","cream","is","awesome"],
- ["this","is","a","long","sentence"]
- ]
- let dataConcat = data.map(item=>item.reduce((a,i)=>`${a} ${i}`))
- // 結(jié)果
- ['The red horse',
- 'Plane over the ocean',
- 'Chocolate ice cream is awesome',
- 'this is a long sentence']
在這里我們使用 map 來(lái)遍歷數(shù)組中的每一項(xiàng),我們對(duì)所有的數(shù)組進(jìn)行還原,并將數(shù)組還原成一個(gè)字符串。
移除數(shù)組中的重復(fù)項(xiàng)
- et dupes = [1,2,3,'a','a','f',3,4,2,'d','d']
- let withOutDupes = dupes.reduce((noDupes, curVal) => {
- if (noDupes.indexOf(curVal) === -1) { noDupes.push(curVal) }
- return noDupes
- }, [])
檢查當(dāng)前值是否在累加器數(shù)組上存在,如果沒(méi)有則返回-1,然后添加它。
當(dāng)然可以用 Set 的方式來(lái)快速刪除重復(fù)值,有興趣的可以自己去谷歌一下。
驗(yàn)證括號(hào)
- [..."(())()(()())"].reduce((a,i)=> i==='('?a+1:a-1,0);
- // 0
- [..."((())()(()())"].reduce((a,i)=> i==='('?a+1:a-1,0);
- // 1
- [..."(())()(()()))"].reduce((a,i)=> i==='('?a+1:a-1,0);
- // -1
這是一個(gè)很酷的項(xiàng)目,之前在力扣中有刷到。
按屬性分組
- let obj = [
- {name: 'Alice', job: 'Data Analyst', country: 'AU'},
- {name: 'Bob', job: 'Pilot', country: 'US'},
- {name: 'Lewis', job: 'Pilot', country: 'US'},
- {name: 'Karen', job: 'Software Eng', country: 'CA'},
- {name: 'Jona', job: 'Painter', country: 'CA'},
- {name: 'Jeremy', job: 'Artist', country: 'SP'},
- ]
- let ppl = obj.reduce((group, curP) => {
- let newkey = curP['country']
- if(!group[newkey]){
- group[newkey]=[]
- }
- group[newkey].push(curP)
- return group
- }, [])
這里,我們根據(jù) country 對(duì)第一個(gè)對(duì)象數(shù)組進(jìn)行分組,在每次迭代中,我們檢查鍵是否存在,如果不存在,我們創(chuàng)建一個(gè)數(shù)組,然后將當(dāng)前的對(duì)象添加到該數(shù)組中,并返回組數(shù)組。
你可以用它做一個(gè)函數(shù),用一個(gè)指定的鍵來(lái)分組對(duì)象。
扁平數(shù)組
- let flattened = [[3, 4, 5], [2, 5, 3], [4, 5, 6]].reduce(
- (singleArr, nextArray) => singleArr.concat(nextArray), [])
- // 結(jié)果:[3, 4, 5, 2, 5, 3, 4, 5, 6]
這只是一層,如果有多層,可以用遞歸函數(shù)來(lái)解決,但我不太喜歡在 JS 上做遞歸的東西??。
一個(gè)預(yù)定的方法是使用.flat方法,它將做同樣的事情
- [ [3, 4, 5],
- [2, 5, 3],
- [4, 5, 6]
- ].flat();
只有冪的正數(shù)
- [-3, 4, 7, 2, 4].reduce((acc, cur) => {
- if (cur> 0) {
- let R = cur**2;
- acc.push(R);
- }
- return acc;
- }, []);
- // 結(jié)果
- [16, 49, 4, 144]
反轉(zhuǎn)字符串
- const reverseStr = str=>[...str].reduce((a,v)=>v+a)
這個(gè)方法適用于任何對(duì)象,不僅適用于字符串。調(diào)用reverseStr("Hola"),輸出的結(jié)果是aloH。
二進(jìn)制轉(zhuǎn)十進(jìn)制
- const bin2dec = str=>[...String(str)].reduce((acc,cur)=>+cur+acc*2,0)
- // 等價(jià)于
- const bin2dec = (str) => {
- return [...String(str)].reduce((acc,cur)=>{
- return +cur+acc*2
- },0)
- }
為了說(shuō)明這一點(diǎn),讓我們看一個(gè)例子:(10111)->1+(1+(1+(0+(1+0*2)*2)*2)*2)*2。
~完,我是刷碗智,勵(lì)志等退休后,要回家擺地?cái)偟娜耍覀兿缕谝?jiàn)!
作者:Ramgen 譯者:前端小智 來(lái)源:dev 原文:https://dev.to/ramgendepy/learn-javascript-reduce-method-with-5-examples-128n