JS數組reduce你不得不知道的25個高級用法
前言
reduce作為ES5新增的常規(guī)數組方法之一,對比forEach、filter和map,在實際使用上好像有些被忽略,發(fā)現身邊的人極少使用它,導致這個如此強大的方法被逐漸埋沒。
如果經常使用reduce,怎么可能放過如此好用的它呢!我還是得把他從塵土中取出來擦干凈,奉上它的高級用法給大家。一個如此好用的方法不應該被大眾埋沒。
下面對reduce的語法進行簡單說明,詳情可查看MDN的reduce()的相關說明。
- 定義:對數組中的每個元素執(zhí)行一個自定義的累計器,將其結果匯總為單個返回值
- 形式:array.reduce((t, v, i, a) => {}, initValue)
- 參數
- callback:回調函數(必選)
- initValue:初始值(可選)
- 回調函數的參數
- total(t):累計器完成計算的返回值(必選)
- value(v):當前元素(必選)
- index(i):當前元素的索引(可選)
- array(a):當前元素所屬的數組對象(可選)
- 過程
- 以t作為累計結果的初始值,不設置t則以數組第一個元素為初始值
- 開始遍歷,使用累計器處理v,將v的映射結果累計到t上,結束此次循環(huán),返回t
- 進入下一次循環(huán),重復上述操作,直至數組最后一個元素
- 結束遍歷,返回最終的t
reduce的精華所在是將累計器逐個作用于數組成員上,把上一次輸出的值作為下一次輸入的值。下面舉個簡單的栗子,看看reduce的計算結果。
const arr = [3, 5, 1, 4, 2]; const a = arr.reduce((t, v) => t + v); // 等同于 const b = arr.reduce((t, v) => t + v, 0);
代碼不太明白沒關系,貼一個reduce的作用動圖應該就會明白了。

reduce實質上是一個累計器函數,通過用戶自定義的累計器對數組成員進行自定義累計,得出一個由累計器生成的值。另外reduce還有一個胞弟reduceRight,兩個方法的功能其實是一樣的,只不過reduce是升序執(zhí)行,reduceRight是降序執(zhí)行。
對空數組調用reduce()和reduceRight()是不會執(zhí)行其回調函數的,可認為reduce()對空數組無效
高級用法
單憑以上一個簡單栗子不足以說明reduce是個什么。為了展示reduce的魅力,我為大家提供25種場景來應用reduce的高級用法。有部分高級用法可能需要結合其他方法來實現,這樣為reduce的多元化提供了更多的可能性。
部分示例代碼的寫法可能有些騷,看得不習慣可自行整理成自己的習慣寫法
累加累乘
function Accumulation(...vals) {
return vals.reduce((t, v) => t + v, 0);
}
function Multiplication(...vals) {
return vals.reduce((t, v) => t * v, 1);
}
Accumulation(1, 2, 3, 4, 5); // 15 Multiplication(1, 2, 3, 4, 5); // 120
權重求和
const scores = [
{ score: 90, subject: "chinese", weight: 0.5 },
{ score: 95, subject: "math", weight: 0.3 },
{ score: 85, subject: "english", weight: 0.2 }
];
const result = scores.reduce((t, v) => t + v.score * v.weight, 0); // 90.5
代替reverse
function Reverse(arr = []) {
return arr.reduceRight((t, v) => (t.push(v), t), []);
}
Reverse([1, 2, 3, 4, 5]); // [5, 4, 3, 2, 1]
代替map和filter
const arr = [0, 1, 2, 3]; // 代替map:[0, 2, 4, 6] const a = arr.map(v => v * 2); const b = arr.reduce((t, v) => [...t, v * 2], []); // 代替filter:[2, 3] const c = arr.filter(v => v > 1); const d = arr.reduce((t, v) => v > 1 ? [...t, v] : t, []); // 代替map和filter:[4, 6] const e = arr.map(v => v * 2).filter(v => v > 2); const f = arr.reduce((t, v) => v * 2 > 2 ? [...t, v * 2] : t, []);
代替some和every
const scores = [
{ score: 45, subject: "chinese" },
{ score: 90, subject: "math" },
{ score: 60, subject: "english" }
];
// 代替some:至少一門合格
const isAtLeastOneQualified = scores.reduce((t, v) => t || v.score >= 60, false); // true
// 代替every:全部合格
const isAllQualified = scores.reduce((t, v) => t && v.score >= 60, true); // false
數組分割
function Chunk(arr = [], size = 1) {
return arr.length ? arr.reduce((t, v) => (t[t.length - 1].length === size ? t.push([v]) : t[t.length - 1].push(v), t), [[]]) : [];
}
const arr = [1, 2, 3, 4, 5]; Chunk(arr, 2); // [[1, 2], [3, 4], [5]]
數組過濾
function Difference(arr = [], oarr = []) {
return arr.reduce((t, v) => (!oarr.includes(v) && t.push(v), t), []);
}
const arr1 = [1, 2, 3, 4, 5]; const arr2 = [2, 3, 6] Difference(arr1, arr2); // [1, 4, 5]
數組填充
function Fill(arr = [], val = "", start = 0, end = arr.length) {
if (start < 0 || start >= end || end > arr.length) return arr;
return [
...arr.slice(0, start),
...arr.slice(start, end).reduce((t, v) => (t.push(val || v), t), []),
...arr.slice(end, arr.length)
];
}
const arr = [0, 1, 2, 3, 4, 5, 6]; Fill(arr, "aaa", 2, 5); // [0, 1, "aaa", "aaa", "aaa", 5, 6]
數組扁平
function Flat(arr = []) {
return arr.reduce((t, v) => t.concat(Array.isArray(v) ? Flat(v) : v), [])
}
const arr = [0, 1, [2, 3], [4, 5, [6, 7]], [8, [9, 10, [11, 12]]]]; Flat(arr); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
數組去重
function Uniq(arr = []) {
return arr.reduce((t, v) => t.includes(v) ? t : [...t, v], []);
}
const arr = [2, 1, 0, 3, 2, 1, 2]; Uniq(arr); // [2, 1, 0, 3]
數組最大最小值
function Max(arr = []) {
return arr.reduce((t, v) => t > v ? t : v);
}
function Min(arr = []) {
return arr.reduce((t, v) => t < v ? t : v);
}
const arr = [12, 45, 21, 65, 38, 76, 108, 43]; Max(arr); // 108 Min(arr); // 12
數組成員獨立拆解
function Unzip(arr = []) {
return arr.reduce(
(t, v) => (v.forEach((w, i) => t[i].push(w)), t),
Array.from({ length: Math.max(...arr.map(v => v.length)) }).map(v => [])
);
}
const arr = [["a", 1, true], ["b", 2, false]]; Unzip(arr); // [["a", "b"], [1, 2], [true, false]]
數組成員個數統計
function Count(arr = []) {
return arr.reduce((t, v) => (t[v] = (t[v] || 0) + 1, t), {});
}
const arr = [0, 1, 1, 2, 2, 2];
Count(arr); // { 0: 1, 1: 2, 2: 3 }
此方法是字符統計和單詞統計的原理,入參時把字符串處理成數組即可
數組成員位置記錄
function Position(arr = [], val) {
return arr.reduce((t, v, i) => (v === val && t.push(i), t), []);
}
const arr = [2, 1, 5, 4, 2, 1, 6, 6, 7]; Position(arr, 2); // [0, 4]
數組成員特性分組
function Group(arr = [], key) {
return key ? arr.reduce((t, v) => (!t[v[key]] && (t[v[key]] = []), t[v[key]].push(v), t), {}) : {};
}
const arr = [
{ area: "GZ", name: "YZW", age: 27 },
{ area: "GZ", name: "TYJ", age: 25 },
{ area: "SZ", name: "AAA", age: 23 },
{ area: "FS", name: "BBB", age: 21 },
{ area: "SZ", name: "CCC", age: 19 }
]; // 以地區(qū)area作為分組依據
Group(arr, "area"); // { GZ: Array(2), SZ: Array(2), FS: Array(1) }
數組成員所含關鍵字統計
function Keyword(arr = [], keys = []) {
return keys.reduce((t, v) => (arr.some(w => w.includes(v)) && t.push(v), t), []);
}
const text = [
"今天天氣真好,我想出去釣魚",
"我一邊看電視,一邊寫作業(yè)",
"小明喜歡同桌的小紅,又喜歡后桌的小君,真TM花心",
"最近上班喜歡摸魚的人實在太多了,代碼不好好寫,在想入非非"
];
const keyword = ["偷懶", "喜歡", "睡覺", "摸魚", "真好", "一邊", "明天"];
Keyword(text, keyword); // ["喜歡", "摸魚", "真好", "一邊"]
字符串翻轉
function ReverseStr(str = "") {
return str.split("").reduceRight((t, v) => t + v);
}
const str = "reduce最牛逼"; ReverseStr(str); // "逼牛最ecuder"
數字千分化
function ThousandNum(num = 0) {
const str = (+num).toString().split(".");
const int = nums => nums.split("").reverse().reduceRight((t, v, i) => t + (i % 3 ? v : `${v},`), "").replace(/^,|,$/g, "");
const dec = nums => nums.split("").reduce((t, v, i) => t + ((i + 1) % 3 ? v : `${v},`), "").replace(/^,|,$/g, "");
return str.length > 1 ? `${int(str[0])}.${dec(str[1])}` : int(str[0]);
}
ThousandNum(1234); // "1,234" ThousandNum(1234.00); // "1,234" ThousandNum(0.1234); // "0.123,4" ThousandNum(1234.5678); // "1,234.567,8"
異步累計
async function AsyncTotal(arr = []) {
return arr.reduce(async(t, v) => {
const at = await t;
const todo = await Todo(v);
at[v] = todo;
return at;
}, Promise.resolve({}));
}
const result = await AsyncTotal(); // 需要在async包圍下使用
斐波那契數列
function Fibonacci(len = 2) {
const arr = [...new Array(len).keys()];
return arr.reduce((t, v, i) => (i > 1 && t.push(t[i - 1] + t[i - 2]), t), [0, 1]);
}
Fibonacci(10); // [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
URL參數反序列化
function ParseUrlSearch() {
return location.search.replace(/(^\?)|(&$)/g, "").split("&").reduce((t, v) => {
const [key, val] = v.split("=");
t[key] = decodeURIComponent(val);
return t;
}, {});
}
// 假設URL為:https://www.baidu.com?age=25&name=TYJ
ParseUrlSearch(); // { age: "25", name: "TYJ" }
URL參數序列化
function StringifyUrlSearch(search = {}) {
return Object.entries(search).reduce(
(t, v) => `${t}${v[0]}=${encodeURIComponent(v[1])}&`,
Object.keys(search).length ? "?" : ""
).replace(/&$/, "");
}
StringifyUrlSearch({ age: 27, name: "YZW" }); // "?age=27&name=YZW"
返回對象指定鍵值
function GetKeys(obj = {}, keys = []) {
return Object.keys(obj).reduce((t, v) => (keys.includes(v) && (t[v] = obj[v]), t), {});
}
const target = { a: 1, b: 2, c: 3, d: 4 };
const keyword = ["a", "d"];
GetKeys(target, keyword); // { a: 1, d: 4 }
數組轉對象
const people = [
{ area: "GZ", name: "YZW", age: 27 },
{ area: "SZ", name: "TYJ", age: 25 }
];
const map = people.reduce((t, v) => {
const { name, ...rest } = v;
t[name] = rest;
return t;
}, {}); // { YZW: {…}, TYJ: {…} }
Redux Compose函數原理
function Compose(...funs) {
if (funs.length === 0) {
return arg => arg;
}
if (funs.length === 1) {
return funs[0];
}
return funs.reduce((t, v) => (...arg) => t(v(...arg)));
}
兼容和性能
好用是挺好用的,但是兼容性如何呢?在Caniuse上搜索一番,兼容性絕對的好,可大膽在任何項目上使用。不要吝嗇你的想象力,盡情發(fā)揮reduce的compose技能啦。對于時常做一些累計的功能,reduce絕對是首選方法。


另外,有些同學可能會問,reduce的性能又如何呢?下面我們通過對for、forEach、map和reduce四個方法同時做1~100000的累加操作,看看四個方法各自的執(zhí)行時間。
// 創(chuàng)建一個長度為100000的數組
const list = [...new Array(100000).keys()];
// for
console.time("for");
let result1 = 0;
for (let i = 0; i < list.length; i++) {
result1 += i + 1;
}
console.log(result1);
console.timeEnd("for");
// forEach
console.time("forEach");
let result2 = 0;
list.forEach(v => (result2 += v + 1));
console.log(result2);
console.timeEnd("forEach");
// map
console.time("map");
let result3 = 0;
list.map(v => (result3 += v + 1, v));
console.log(result3);
console.timeEnd("map");
// reduce
console.time("reduce");
const result4 = list.reduce((t, v) => t + v + 1, 0);
console.log(result4);
console.timeEnd("reduce");
| 累加操作 | 執(zhí)行時間 |
|---|---|
| for | 6.719970703125ms |
| forEach | 3.696044921875ms |
| map | 3.554931640625ms |
| reduce | 2.806884765625ms |
以上代碼在MacBook Pro 2019 15寸 16G內存 512G閃存的Chrome 79下執(zhí)行,不同的機器不同的環(huán)境下執(zhí)行以上代碼都有可能存在差異。
我已同時測試過多臺機器和多個瀏覽器,連續(xù)做了10次以上操作,發(fā)現reduce總體的平均執(zhí)行時間還是會比其他三個方法稍微快一點,所以大家還是放心使用啦!本文更多是探討reduce的使用技巧,如對reduce的兼容和性能存在疑問,可自行參考相關資料進行驗證。
最后,送大家一張reduce生成的乘法口訣表:一七得七,二七四十八,三八婦女節(jié),五一勞動節(jié),六一兒童節(jié)。


總結
到此這篇關于JS數組reduce你不得不知道的25個高級用法的文章就介紹到這了,更多相關JS數組reduce高級用法內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
javascript通過元素id和name直接取得元素的方法
這篇文章主要介紹了javascript通過元素id和name直接取得元素的方法,涉及javascript獲取元素的相關技巧,非常具有實用價值,需要的朋友可以參考下2015-04-04

