数组-Reduce

130 阅读4分钟

一、初衷

reduce很强大的方法,发现同事有使用:我看一眼代码,不像forEach、filter、map、some、every一样,脑海中能直接明白逻辑和意思,需要脑筋转个弯。

举例🌰,如果你一眼看明白了,请出门左转慢走!(证明你已经掌握了)

// 例子1
const cssText = Object.entries(style).reduce((prev, next) => {
  const [k, v] = next
  return prev + `${k}:${v};`
}, '')

// 例子2
const names = [
    "baseUomLevel1Price",
    "baseUomLevel2Price",
    "baseUomLevel3Price",
    "baseUomLevel4Price",
    "baseUomLevel5Price",

]
const models = names.reduce((ret, next) => {
    let propName = next.replace('baseUom', '')
    if(!viewModel.get(next)) return ret
    return [
        ...ret,
        {
            name: propName.charAt(0).toLowerCase() + propName.slice(1),
            model: viewModel.get(next)
        }
    ]
}, []);

所以总结一下用法:方便熟练掌握。

二、说明和常用方式

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

  • 定义:对数组中的每个元素执行一个自定义的累计器,将其结果汇总为单个返回值

  • 形式: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的精华所在是将累计器逐个作用于数组成员上,把上一次输出的值作为下一次输入的值

reduceRight,两个方法的功能其实是一样的,只不过reduce是升序执行,reduceRight是降序执行(从右向左,开始)。

const style ={name: 'lxq', width: '100px'};
const cssText = Object.entries(style).reduce((prev, next) => {
  const [k, v] = next
  return prev + `${k}:${v};`
}, '')

console.log(cssText); // name:lxq;width:100px;
const style ={name: 'lxq', width: '100px'};
const cssText = Object.entries(style).reduceRight((prev, next) => {
  const [k, v] = next
  return prev + `${k}:${v};`
}, '')

console.log(cssText); // width:100px;name:lxq;

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

[].reduce((pre,next)=>{
    return pre + 'lxq';
},'')

// ''

三、强大用法

累加累乘
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
返回对象指定键值
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 }
数组拍平
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 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 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]
数组转对象
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: {…} }
数字千分化
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"
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)));
}

四、阅读感想

1、参考了一些文章,不常用的例子(部分示例代码的写法可能有些骚)有阅读,但没有搜集整理,感觉一万年可能也用不上。

2、至于其他文章分析的 for、forEach 、map 、reduce 性能分析,有点局限性(四个方法同时做1~100000的累加操作)。参考性不大,但是reduce 性能很好是肯定的。其他api 要看处理什么场景,对应使用合适的api,语义和性能都ok!

3、兼容性:都2022年了。这个api 再不试试都老了🌶。

参考的文章

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

JS数组reduce()方法