JavaScript数组reduce高阶函数:从基础语法到20种实战场景详解

作者:小括号

时间:2026-10-26

浏览:82

本文深入解析JavaScript数组reduce高阶函数的核心原理与语法结构,详细阐述累加器、当前值及初始参数的作用机制。通过求和、平均数、最大值等基础示例,逐步过渡到数组去重、分组统计、扁平化、Promise串行执行等20种高级应用场景,帮助开发者掌握利用reduce实现复杂数据操作的核心技巧。

文章目录

reduce 属于 JavaScript 数组内置的高阶函数

该函数遍历数组各元素,最终输出单一结果值。

标准调用格式为:array.reduce(callback[, initialValue])

callback 接收四个参数:累加器(初始值或前次回调返回值)、当前项、当前索引、原数组。initialValue 为可选初始值,若未提供,则累加器初始化为数组首元素。reduce 从首元素起依次执行回调,回调返回值作为下次调用的累加器,最终返回累加结果。以下为计算数组元素总和的简单示例:

const arr = [1, 2, 3, 4, 5];
const sum = arr.reduce((accumulator, currentValue) => accumulator + currentValue);
console.log(sum); // 15

上述代码中,reduce 从首元素开始累加,最终输出结果 15。除求和外,reduce 还可用于计算平均数、最大值、最小值等。此外,它可与 map、filter、forEach 等函数配合,完成更复杂的数据处理任务。

以下列举 reduce 的实际应用场景,助您深入理解:

计算数组平均数

const arr = [1, 2, 3, 4, 5];
const average = arr.reduce((accumulator, currentValue, index, array) => {
  accumulator += currentValue;
  if (index === array.length - 1) {
    return accumulator / array.length;
  } else {
    return accumulator;
  }
});
console.log(average); // 3

求数组最大值

const arr = [1, 2, 3, 4, 5];
const max = arr.reduce((accumulator, currentValue) => Math.max(accumulator, currentValue));
console.log(max); // 5

求数组最小值

const arr = [1, 2, 3, 4, 5];
const min = arr.reduce((accumulator, currentValue) => Math.min(accumulator, currentValue));
console.log(min); // 1

数组去重处理

const arr = [1, 2, 3, 3, 4, 4, 5];
const uniqueArr = arr.reduce((accumulator, currentValue) => {
  if (!accumulator.includes(currentValue)) {
    accumulator.push(currentValue);
  }
  return accumulator;
}, []);
console.log(uniqueArr); // [1, 2, 3, 4, 5]

统计数组元素出现频次

const arr = [1, 2, 3, 3, 4, 4, 5];
const countMap = arr.reduce((accumulator, currentValue) => {
  if (!accumulator[currentValue]) {
    accumulator[currentValue] = 1;
  } else {
    accumulator[currentValue]++;
  }
  return accumulator;
}, {});
console.log(countMap); // {1: 1, 2: 1, 3: 2, 4: 2, 5: 1}

实现数组分组逻辑

const arr = [1, 2, 3, 4, 5];
const result = arr.reduce((accumulator, currentValue) => {
  if (currentValue % 2 === 0) {
    accumulator.even.push(currentValue);
  } else {
    accumulator.odd.push(currentValue);
  }
  return accumulator;
}, { even: [], odd: [] });
console.log(result); // {even: [2, 4], odd: [1, 3, 5]}

计算连续递增数字序列长度

const arr = [1, 2, 3, 5, 6, 7, 8, 9];
const result = arr.reduce((accumulator, currentValue, index, array) => {
  if (index === 0 || currentValue !== array[index - 1] + 1) {
    accumulator.push([currentValue]);
  } else {
    accumulator[accumulator.length - 1].push(currentValue);
  }
  return accumulator;
}, []);
const maxLength = result.reduce((accumulator, currentValue) => Math.max(accumulator, currentValue.length), 0);
console.log(maxLength); // 5

统计对象数组属性总和

const arr = [
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 30 },
  { name: 'Charlie', age: 35 },
];
const result = arr.reduce((accumulator, currentValue) => accumulator + currentValue.age, 0);
console.log(result); // 90

将对象数组转为键值对对象

const arr = [
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 30 },
  { name: 'Charlie', age: 35 },
];
const result = arr.reduce((accumulator, currentValue) => {
  accumulator[currentValue.name] = currentValue.age;
  return accumulator;
}, {});
console.log(result); // {Alice: 25, Bob: 30, Charlie: 35}

查找数组中出现频率最高的元素

const arr = [1, 2, 3, 4, 4, 4, 5, 5, 6, 6, 6, 6];
const result = arr.reduce((accumulator, currentValue) => {
  accumulator[currentValue] = (accumulator[currentValue] || 0) + 1;
  return accumulator;
}, {});
const maxCount = Math.max(...Object.values(result));
const mostFrequent = Object.keys(result).filter(key => result[key] === maxCount).map(Number);
console.log(mostFrequent); // [6]

实现 Promise 串行执行逻辑

const promise1 = () => Promise.resolve('one');
const promise2 = (input) => Promise.resolve(input + ' two');
const promise3 = (input) => Promise.resolve(input + ' three');
const promises = [promise1, promise2, promise3];
const result = promises.reduce((accumulator, currentValue) => {
  return accumulator.then(currentValue);
}, Promise.resolve('start'));
result.then(console.log); // 'one two three'

对象属性值求和

const obj = {
  a: 1,
  b: 2,
  c: 3
};
const result = Object.values(obj).reduce((accumulator, currentValue) => accumulator + currentValue);
console.log(result); // 6

按指定属性对数组进行分组

const arr = [
  { id: 1, name: 'John' },
  { id: 2, name: 'Mary' },
  { id: 3, name: 'Bob' },
  { id: 4, name: 'Mary' }
];
const result = arr.reduce((accumulator, currentValue) => {
  const key = currentValue.name;
  if (!accumulator[key]) {
    accumulator[key] = [];
  }
  accumulator[key].push(currentValue);
  return accumulator;
}, {});
console.log(result);
/*
{
  John: [{ id: 1, name: 'John' }],
  Mary: [
    { id: 2, name: 'Mary' },
    { id: 4, name: 'Mary' }
  ],
  Bob: [{ id: 3, name: 'Bob' }]
}
*/

数组扁平化处理

// 如果你有一个嵌套的数组,可以使用reduce将其扁平化成一个一维数组。例如:
const nestedArray = [[1, 2], [3, 4], [5, 6]];
const flattenedArray = nestedArray.reduce((acc, curr) => acc.concat(curr), []);
console.log(flattenedArray); // [1, 2, 3, 4, 5, 6]

多个对象合并操作

// 可以使用reduce将多个对象合并成一个对象。例如:
const obj1 = { a: 1, b: 2 };
const obj2 = { c: 3, d: 4 };
const obj3 = { e: 5, f: 6 };
const mergedObj = [obj1, obj2, obj3].reduce((acc, curr) => Object.assign(acc, curr), {});
console.log(mergedObj); // {a: 1, b: 2, c: 3, d: 4, e: 5, f: 6}

以上为 JavaScript 数组高阶函数 reduce 的详细解析,更多相关技术内容敬请查阅本站其他文章!

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章