17370845950

JS数组方法剖析_Reduce高级用法
reduce的核心是累积计算,可实现数组扁平化、groupBy分组、函数组合compose及构建复杂对象结构,适用于数据处理、转换和聚合场景。

reduce 是 JavaScript 数组中功能最强大的方法之一,它不只是用来求和。通过合理利用其累加机制,可以实现很多复杂的数据处理逻辑。它的核心思想是“累积计算”,将数组的每一项逐步合并为一个最终结果。

reduce 基本语法回顾

reduce 方法接收两个参数:一个回调函数和一个可选的初始值。

array.reduce((accumulator, current, index, array) => {
  // 返回新的 accumulator
}, initialValue);

accumulator:上一次调用回调返回的值,或者是提供的初始值。
current:当前遍历的元素。
index:当前元素的索引(可选)。
array:原数组(可选)。

高级用法一:扁平化嵌套数组

使用 reduce 可以替代 flat 方法,实现任意层级的数组扁平化。

例如,将多层嵌套数组拍平:

const nested = [1, [2, [3, [4]], 5]];

const flatten = arr => arr.reduce((acc, val) => Array.isArray(val) ? acc.concat(flatten(val)) : acc.concat(val), []);

flatten(nested); // [1, 2, 3, 4, 5]

这个递归结构让 reduce 能深入每一层,灵活控制拍平逻辑。

高级用法二:按条件分组数据(groupBy)

reduce 可以代替 lodash 的 groupBy 实现对象分类。

比如根据用户年龄分组:

const users = [
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 30 },
  { name: 'Charlie', age: 25 }
];

const groupBy = (arr, key) => arr.reduce((acc, item) => { const groupKey = item[key]; if (!acc[groupKey]) acc[groupKey] = []; acc[groupKey].push(item); return acc; }, {});

groupBy(users, 'age'); // {25: [{name: 'Alice'...}, {name: 'Charlie'...}], 30: [{name: 'Bob'...}]}

这种模式在处理后端返回的原始数据时非常实用。

高级用法三:链式操作与函数组合

结合 reduce 可以实现函数式编程中的 compose(函数组合)。

将多个函数从右到左依次执行:

const compose = (...fns) => 
  (value) => fns.reduceRight((acc, fn) => fn(acc), value);

const addOne = x => x + 1; const double = x => x * 2; const subtractThree = x => x - 3;

const pipeline = compose(subtractThree, double, addOne); pipeline(5); // ((5 + 1) * 2) - 3 = 9

这种写法常用于中间件处理、数据转换流程等场景。

高级用法四:构建状态机或复杂对象结构

当需要根据数组生成复杂对象时,reduce 比 forEach 更具表达力。

例如,统计字符出现频率:

const str = 'hello';
const charCount = [...str].reduce((acc, char) => {
  acc[char] = (acc[char] || 0) + 1;
  return acc;
}, {});

// { h: 1, e: 1, l: 2, o: 1 }

同样适用于构建树形结构、路径映射表等场景。

基本上就这些。reduce 的强大在于它把“遍历+积累”的过程抽象成一种通用模式。只要你想从数组中“提炼”出某种结构或值,reduce 往往是最合适的工具。