Skip to content

映射, 筛选, Reduce in 深度

Mastering functional 数组 transformation, 筛选, and accumulation 模式.

你将学到

  • 映射: transforming 每个元素到 新数组
  • 筛选: keeping 元素那个通过 predicate
  • reduce: accumulating 所有元素到 one 值
  • Chaining 映射/筛选/reduce for 数据流水线
  • 常见 pitfalls: forgetting 初始值 and mutating in 回调

概念讲解

The Functional Trio

映射, 筛选, and reduce are the three foundational functional array methods. They treat arrays as data to transform, not as mutable storage to modify in place. Each returns a new array (or value for reduce), leaving the original untouched. This immutability makes code easier to reason about and is the backbone of modern data processing in React, Node, and functional libraries.

map — Transform

映射(fn) applies fn to every element and returns a new array of the same length. The callback receives (element, index, array). Use map when you have a one-to-one transformation: every input element produces exactly one output element. It is the array equivalent of a mathematical function applied element-wise.

filter — Select

筛选(predicate) keeps only the elements for which the predicate returns a truthy value. The result array may be shorter than the input. The callback receives (element, index, array). Use filter when you want a subset based on a condition — it is the declarative replacement for a manual loop with push.

reduce — Accumulate

reduce(fn, initialValue) walks the array left to right, carrying an accumulator that is updated by each step. The callback receives (accumulator, element, index, array). It is the most powerful of the three: map and filter can be implemented with reduce. Use it to sum, flatten, group, count, or build any single value from an array. Always pass an initial value to avoid the subtle behavior where the first element is used as the initial accumulator when one is omitted.

Chaining

Because each method returns a new array, you can chain them into a readable data pipeline: 数据.筛选(...).映射(...).reduce(...). Each step is a small, testable transformation. The trade-off is that chaining creates intermediate arrays; for very large datasets, a single reduce or a for loop may be more efficient. Optimize only when profiling shows a real bottleneck.

Composition Over Mutation

The functional style favors composing small pure functions over writing one big imperative loop. This scales better: each step is independent, testable, and reusable. The key discipline is to never mutate inside the callbacks — return new values, and let the methods build the result arrays.

示例代码

              const orders = [
  { id: 1, customer: "Ada", total: 120, status: "shipped" },
  { id: 2, customer: "Alan", total: 85, status: "pending" },
  { id: 3, customer: "Ada", total: 200, status: "shipped" },
  { id: 4, customer: "Grace", total: 50, status: "cancelled" },
  { id: 5, customer: "Alan", total: 300, status: "shipped" },
];

// Pipeline: filter shipped → map to total → reduce to sum
const shippedRevenue = orders
  .filter((o) => o.status === "shipped")
  .map((o) => o.total)
  .reduce((sum, total) => sum + total, 0);
console.log("Shipped revenue:", shippedRevenue); // 620

// reduce to group by customer
const byCustomer = orders.reduce((groups, order) => {
  const key = order.customer;
  (groups[key] ??= []).push(order);
  return groups;
}, {});
console.log("By customer:", Object.keys(byCustomer));

// reduce to find the max total
const maxOrder = orders.reduce(
  (max, o) => (o.total > max.total ? o : max),
  orders[0]
);
console.log("Largest order:", maxOrder.id, maxOrder.total);

// map to transform shape, filter to drop cancelled
const summaries = orders
  .filter((o) => o.status !== "cancelled")
  .map((o) => ({ id: o.id, label: `${o.customer} — $${o.total}` }));
console.log("Summaries:", summaries);

// flatten with reduce
const nested = [[1, 2], [3, 4], [5]];
const flat = nested.reduce((acc, arr) => [...acc, ...arr], []);
console.log("Flat:", flat); // [1, 2, 3, 4, 5]
            

Shows 筛选→映射→reduce revenue 流水线, 分组通过 customer 使用 reduce, 查找最大值使用 reduce, transforming shape 使用映射+筛选, and flattening nested 数组使用 reduce.

动手试一试

  • JSON Formatter

    格式数组的 对象你 transform 使用映射/筛选/reduce.

  • CSV 到 JSON

    Convert CSV 到数组的 对象, 然后处理它们 functionally.

常见错误

错误写法

Forgetting 初始值 in reduce

正确做法

不使用初始值, reduce uses 首先元素 as accumulator and skips 它. 这个 causes bugs 当数组是 空 or accumulator 类型 differs 从元素类型. 总是通过 explicit 初始值 as 其次实参.

错误写法

Mutating 原始数组 or 它的元素内部映射/筛选回调

正确做法

映射, 筛选, and reduce 是 meant 到是 pure. Mutating 元素 or 源数组 breaks immutability and causes subtle bugs. 返回新 对象/数组从 回调 and 从不 call 推送 or splice on 输入.

相关代码片段

相关速查表

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

动手做项目

通过引导式项目应用所学,含起始代码与解决方案。

查看项目

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误