25个你不得不知道的数组reduce高级用法

开发 前端
如果经常使用reduce,怎么可能放过如此好用的它呢!我还是得把他从尘土中取出来擦干净,奉上它的高级用法给大家。一个如此好用的方法不应该被大众埋没。

背景

距离上一篇技术文章《1.5万字概括ES6全部特性》发布到现在,已经有整整4个月没有输出过一篇技术文章了。哈哈,不是不想写,而是实在太忙,这段时间每天不是上班就是加班,完全没有自己的时间。这篇文章也是抽空之余完成,希望大家喜欢,谢谢大家继续支持我。

本文首发于『搜狐技术产品』公众号,首发内容与博客内容略有不同,博客内容今早发布时额外有所增加

reduce作为ES5新增的常规数组方法之一,对比forEach、filter和map,在实际使用上好像有些被忽略,发现身边的人极少使用它,导致这个如此强大的方法被逐渐埋没。

如果经常使用reduce,怎么可能放过如此好用的它呢!我还是得把他从尘土中取出来擦干净,奉上它的高级用法给大家。一个如此好用的方法不应该被大众埋没。

下面对reduce的语法进行简单说明,详情可查看MDN的reduce()的相关说明。

  •  定义:对数组中的每个元素执行一个自定义的累计器,将其结果汇总为单个返回值
  •  形式:array.reduce((t, v, i, a) => {}, initValue)
  •  参数
    •   callback:回调函数(必选)
    •   initValue:初始值(可选)
  •  回调函数的参数
    •   total(t):累计器完成计算的返回值(必选)
    •   value(v):当前元素(必选)
    •   index(i):当前元素的索引(可选)
    •   array(a):当前元素所属的数组对象(可选)
  •  过程
    •   以t作为累计结果的初始值,不设置t则以数组第一个元素为初始值
    •   开始遍历,使用累计器处理v,将v的映射结果累计到t上,结束此次循环,返回t
    •   进入下一次循环,重复上述操作,直至数组最后一个元素
    •   结束遍历,返回最终的t

reduce的精华所在是将累计器逐个作用于数组成员上,把上一次输出的值作为下一次输入的值。下面举个简单的栗子,看看reduce的计算结果。 

  1. const arr = [3, 5, 1, 4, 2];  
  2. const a = arr.reduce((t, v) => t + v);  
  3. // 等同于  
  4. const b = arr.reduce((t, v) => t + v, 0); 

reduce实质上是一个累计器函数,通过用户自定义的累计器对数组成员进行自定义累计,得出一个由累计器生成的值。另外reduce还有一个胞弟reduceRight,两个方法的功能其实是一样的,只不过reduce是升序执行,reduceRight是降序执行。

对空数组调用reduce()和reduceRight()是不会执行其回调函数的,可认为reduce()对空数组无效

高级用法

单凭以上一个简单栗子不足以说明reduce是个什么。为了展示reduce的魅力,我为大家提供25种场景来应用reduce的高级用法。有部分高级用法可能需要结合其他方法来实现,这样为reduce的多元化提供了更多的可能性。

部分示例代码的写法可能有些骚,看得不习惯可自行整理成自己的习惯写法

  • 累加累乘 
  1. function Accumulation(...vals) {  
  2.     return vals.reduce((t, v) => t + v, 0);  
  3.  
  4. function Multiplication(...vals) {  
  5.     return vals.reduce((t, v) => t * v, 1);  
  6.  
  1. Accumulation(1, 2, 3, 4, 5); // 15  
  2. Multiplication(1, 2, 3, 4, 5); // 120 
  • 权重求和 
  1. const scores = [  
  2.     { score: 90, subject: "chinese", weight: 0.5 },  
  3.     { score: 95, subject: "math", weight: 0.3 },  
  4.     { score: 85, subject: "english", weight: 0.2 }  
  5. ];  
  6. const result = scores.reduce((t, v) => t + v.score * v.weight, 0); // 90.5 
  • 代替reverse 
  1. function Reverse(arr = []) {  
  2.     return arr.reduceRight((t, v) => (t.push(v), t), []);  
  3.  
  1. Reverse([1, 2, 3, 4, 5]); // [5, 4, 3, 2, 1] 
  • 代替map和filter 
  1. const arr = [0, 1, 2, 3];  
  2. // 代替map:[0, 2, 4, 6]  
  3. const a = arr.map(v => v * 2);  
  4. const b = arr.reduce((t, v) => [...t, v * 2], []);  
  5. // 代替filter:[2, 3]  
  6. const c = arr.filter(v => v > 1);  
  7. const d = arr.reduce((t, v) => v > 1 ? [...t, v] : t, []);  
  8. // 代替map和filter:[4, 6]  
  9. const e = arr.map(v => v * 2).filter(v => v > 2);  
  10. const f = arr.reduce((t, v) => v * 2 > 2 ? [...t, v * 2] : t, []); 
  • 代替some和every 
  1. const scores = [  
  2.     { score: 45, subject: "chinese" },  
  3.     { score: 90, subject: "math" },  
  4.     { score: 60, subject: "english" }  
  5. ];  
  6. // 代替some:至少一门合格  
  7. const isAtLeastOneQualified = scores.reduce((t, v) => v.score >= 60, false); // true  
  8. // 代替every:全部合格  
  9. const isAllQualified = scores.reduce((t, v) => t && v.score >= 60, true); // false 
  • 数组分割 
  1. function Chunk(arr = [], size = 1) {  
  2.     return arr.length ? arr.reduce((t, v) => (t[t.length - 1].length === size ? t.push([v]) : t[t.length - 1].push(v), t), [[]]) : [];  
  3.  
  1. const arr = [1, 2, 3, 4, 5];  
  2. Chunk(arr, 2); // [[1, 2], [3, 4], [5]] 
  • 数组过滤 
  1. function Difference(arr = [], oarr = []) {  
  2.     return arr.reduce((t, v) => (!oarr.includes(v) && t.push(v), t), []);  
  3.  
  1. const arr1 = [1, 2, 3, 4, 5];  
  2. const arr2 = [2, 3, 6]  
  3. Difference(arr1, arr2); // [1, 4, 5] 
  • 数组填充 
  1. function Fill(arr = [], val = ""start = 0end = arr.length) {  
  2.     if (start < 0 || start >= end || end > arr.length) return arr;  
  3.     return [  
  4.         ...arr.slice(0, start),  
  5.         ...arr.slice(start, end).reduce((t, v) => (t.push(val || v), t), []),  
  6.         ...arr.slice(end, arr.length)  
  7.     ];  
  8.  
  1. const arr = [0, 1, 2, 3, 4, 5, 6];  
  2. Fill(arr, "aaa", 2, 5); // [0, 1, "aaa", "aaa", "aaa", 5, 6] 
  • 数组扁平 
  1. function Flat(arr = []) {  
  2.     return arr.reduce((t, v) => t.concat(Array.isArray(v) ? Flat(v) : v), [])  
  3.  
  1. const arr = [0, 1, [2, 3], [4, 5, [6, 7]], [8, [9, 10, [11, 12]]]];  
  2. Flat(arr); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] 
  • 数组去重 
  1. function Uniq(arr = []) {  
  2.     return arr.reduce((t, v) => t.includes(v) ? t : [...t, v], []);  
  3.  
  1. const arr = [2, 1, 0, 3, 2, 1, 2];  
  2. Uniq(arr); // [2, 1, 0, 3] 
  • 数组最大最小值 
  1. function Max(arr = []) {  
  2.     return arr.reduce((t, v) => t > v ? t : v);  
  3.  
  4. function Min(arr = []) {  
  5.     return arr.reduce((t, v) => t < v ? t : v);  
  6.  
  1. const arr = [12, 45, 21, 65, 38, 76, 108, 43];  
  2. Max(arr); // 108  
  3. Min(arr); // 12 
  • 数组成员独立拆解 
  1. function Unzip(arr = []) {  
  2.     return arr.reduce(  
  3.         (t, v) => (v.forEach((w, i) => t[i].push(w)), t),  
  4.         Array.from({ length: Math.max(...arr.map(v => v.length)) }).map(v => [])  
  5.     );  
  6.  
  1. const arr = [["a", 1, true], ["b", 2, false]];  
  2. Unzip(arr); // [["a", "b"], [1, 2], [true, false]] 
  • 数组成员个数统计 
  1. function Count(arr = []) {  
  2.     return arr.reduce((t, v) => (t[v] = (t[v] || 0) + 1, t), {});  
  3.  
  1. const arr = [0, 1, 1, 2, 2, 2];  
  2. Count(arr); // { 0: 1, 1: 2, 2: 3 }  
  1. 此方法是字符统计和单词统计的原理,入参时把字符串处理成数组即可 
  • 数组成员位置记录 
  1. function Position(arr = [], val) {  
  2.     return arr.reduce((t, v, i) => (v === val && t.push(i), t), []);  
  3.  
  1. const arr = [2, 1, 5, 4, 2, 1, 6, 6, 7];  
  2. Position(arr, 2); // [0, 4] 
  • 数组成员特性分组 
  1. function Group(arr = [], key) {  
  2.     return key ? arr.reduce((t, v) => (!t[v[key]] && (t[v[key]] = []), t[v[key]].push(v), t), {}) : {};  
  3.  
  1. const arr = [  
  2.     { area: "GZ", name: "YZW", age: 27 },  
  3.     { area: "GZ", name: "TYJ", age: 25 },  
  4.     { area: "SZ", name: "AAA", age: 23 },  
  5.     { area: "FS", name: "BBB", age: 21 },  
  6.     { area: "SZ", name: "CCC", age: 19 }  
  7. ]; // 以地区area作为分组依据  
  8. Group(arr, "area"); // { GZ: Array(2), SZ: Array(2), FS: Array(1) } 
  • 数组成员所含关键字统计 
  1. function Keyword(arr = [], keys = []) {  
  2.     return keys.reduce((t, v) => (arr.some(w => w.includes(v)) && t.push(v), t), []);  
  3.  
  1. const text = [  
  2.     "今天天气真好,我想出去钓鱼",  
  3.     "我一边看电视,一边写作业",  
  4.     "小明喜欢同桌的小红,又喜欢后桌的小君,真TM花心",  
  5.     "最近上班喜欢摸鱼的人实在太多了,代码不好好写,在想入非非"  
  6. ];  
  7. const keyword = ["偷懒", "喜欢", "睡觉", "摸鱼", "真好", "一边", "明天"];  
  8. Keyword(text, keyword); // ["喜欢", "摸鱼", "真好", "一边"] 
  • 字符串翻转 
  1. function ReverseStr(str = "") {  
  2.     return str.split("").reduceRight((t, v) => t + v);  
  3.  
  1. const str = "reduce最牛逼" 
  2. ReverseStr(str); // "逼牛最ecuder" 
  • 数字千分化 
  1. function ThousandNum(num = 0) {  
  2.     const str = (+num).toString().split(".");  
  3.     const int = nums => nums.split("").reverse().reduceRight((t, v, i) => t + (i % 3 ? v : `${v},`), "").replace(/^,|,$/g, "");  
  4.     const dec = nums => nums.split("").reduce((t, v, i) => t + ((i + 1) % 3 ? v : `${v},`), "").replace(/^,|,$/g, "");  
  5.     return str.length > 1 ? `${int(str[0])}.${dec(str[1])}` : int(str[0]);  
  6.  
  1. ThousandNum(1234); // "1,234"  
  2. ThousandNum(1234.00); // "1,234"  
  3. ThousandNum(0.1234); // "0.123,4"  
  4. ThousandNum(1234.5678); // "1,234.567,8" 
  • 异步累计 
  1. async function AsyncTotal(arr = []) {  
  2.     return arr.reduce(async(t, v) => {  
  3.         const at = await t;  
  4.         const todo = await Todo(v);  
  5.         at[v] = todo;  
  6.         return at;  
  7.     }, Promise.resolve({}));  
  8.  
  1. const result = await AsyncTotal(); // 需要在async包围下使用 
  • 斐波那契数列 
  1. function Fibonacci(len = 2) {  
  2.     const arr = [...new Array(len).keys()];  
  3.     return arr.reduce((t, v, i) => (i > 1 && t.push(t[i - 1] + t[i - 2]), t), [0, 1]);  
  4.  
  1. Fibonacci(10); // [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] 
  • URL参数反序列化 
  1. function ParseUrlSearch() {  
  2.     return location.search.replace(/(^\?)|(&$)/g, "").split("&").reduce((t, v) => {  
  3.         const [key, val] = v.split("=");  
  4.         t[key] = decodeURIComponent(val);  
  5.         return t;  
  6.     }, {});  
  7.  
  1. // 假设URL为:https://www.baidu.com?age=25&name=TYJ  
  2. ParseUrlSearch(); // { age: "25", name: "TYJ" } 
  • URL参数序列化 
  1. function StringifyUrlSearch(search = {}) {  
  2.     return Object.entries(search).reduce(  
  3.         (t, v) => `${t}${v[0]}=${encodeURIComponent(v[1])}&`,  
  4.         Object.keys(search).length ? "?" : ""  
  5.     ).replace(/&$/, "");  
  6.  
  1. StringifyUrlSearch({ age: 27, name: "YZW" }); // "?age=27&name=YZW
  • 返回对象指定键值 
  1. function GetKeys(obj = {}, keys = []) {  
  2.     return Object.keys(obj).reduce((t, v) => (keys.includes(v) && (t[v] = obj[v]), t), {});  
  3.  
  1. const target = { a: 1, b: 2, c: 3, d: 4 };  
  2. const keyword = ["a", "d"];  
  3. GetKeys(target, keyword); // { a: 1, d: 4 } 
  • 数组转对象 
  1. const people = [  
  2.     { area: "GZ", name: "YZW", age: 27 },  
  3.     { area: "SZ", name: "TYJ", age: 25 }  
  4. ];  
  5. const map = people.reduce((t, v) => {  
  6.     const { name, ...rest } = v;  
  7.     t[name] = rest;  
  8.     return t;  
  9. }, {}); // { YZW: {…}, TYJ: {…} } 
  • Redux Compose函数原理 
  1. function Compose(...funs) {  
  2.     if (funs.length === 0) {  
  3.         return arg => arg;  
  4.     }  
  5.     if (funs.length === 1) {  
  6.         return funs[0];  
  7.     }  
  8.     return funs.reduce((t, v) => (...arg) => t(v(...arg)));  

兼容和性能

好用是挺好用的,但是兼容性如何呢?在Caniuse上搜索一番,兼容性绝对的好,可大胆在任何项目上使用。不要吝啬你的想象力,尽情发挥reduce的compose技能啦。对于时常做一些累计的功能,reduce绝对是首选方法。

另外,有些同学可能会问,reduce的性能又如何呢?下面我们通过对for-in、forEach、map和reduce四个方法同时做1~100000的累加操作,看看四个方法各自的执行时间。 

  1. // 创建一个长度为100000的数组  
  2. const list = [...new Array(100000).keys()];  
  3. // for-in  
  4. console.time("for-in");  
  5. let result1 = 0 
  6. for (let i = 0; i < list.length; i++) {  
  7.     result1 += i + 1;  
  8.  
  9. console.log(result1);  
  10. console.timeEnd("for-in");  
  11. // forEach  
  12. console.time("forEach");  
  13. let result2 = 0 
  14. list.forEach(v => (result2 += v + 1));  
  15. console.log(result2);  
  16. console.timeEnd("forEach");  
  17. // map  
  18. console.time("map");  
  19. let result3 = 0 
  20. list.map(v => (result3 += v + 1, v));  
  21. console.log(result3);  
  22. console.timeEnd("map");  
  23. // reduce  
  24. console.time("reduce");  
  25. const result4 = list.reduce((t, v) => t + v + 1, 0);  
  26. console.log(result4);  
  27. console.timeEnd("reduce"); 
累加操作 执行时间
for-in 6.719970703125ms
forEach 3.696044921875ms
map 3.554931640625ms
reduce 2.806884765625ms

以上代码在MacBook Pro 2019 15寸 16G内存 512G闪存的Chrome 79下执行,不同的机器不同的环境下执行以上代码都有可能存在差异。

我已同时测试过多台机器和多个浏览器,连续做了10次以上操作,发现reduce总体的平均执行时间还是会比其他三个方法稍微快一点,所以大家还是放心使用啦!本文更多是探讨reduce的使用技巧,如对reduce的兼容和性能存在疑问,可自行参考相关资料进行验证。

结语

写到最后总结得差不多了,后续如果我想起还有哪些reduce高级用法遗漏的,会继续在这篇文章上补全,同时也希望各位朋友对文章里的要点进行补充或提出自己的见解。欢迎在下方进行评论或补充喔,喜欢的点个赞或收个藏,保证你在开发时用得上。 

 

责任编辑:庞桂玉 来源: segmentfault
相关推荐

2020-10-21 09:36:40

Vue项目技巧

2022-10-27 09:55:00

2022-08-30 23:54:42

MySQL数据库工具

2015-09-23 10:27:04

大数据秘诀

2015-09-22 10:03:25

大数据秘诀

2023-08-29 08:41:42

2017-08-10 16:54:47

MySQL优化MySQL

2022-08-08 11:13:35

API接口前端

2017-11-02 06:51:38

5G移动网络技术

2020-05-18 09:33:27

前端开发工具

2020-09-02 07:30:31

前端Vue.set代码

2019-07-17 10:55:40

Kubernetes工具Katacoda

2017-08-16 18:03:12

Docker安全工具容器

2017-09-22 09:10:41

2009-05-31 09:02:23

2016-03-30 09:56:37

5G

2015-08-17 11:46:07

云计算云服务公有云

2020-08-05 12:17:00

C语言代码分配

2010-08-27 10:40:55

Android

2011-03-31 10:46:54

LinuxCLI软件
点赞
收藏

51CTO技术栈公众号