返回

轻松掌握 reduce 方法,玩转 JS 数组迭代

前端

纵横 JavaScript 数组迭代:reduce 方法的 8 个实用实例

JavaScript 中的 reduce 方法可谓一个鲜为人知的秘密武器,它拥有改变数组处理方式的强大力量。reduce 方法不仅可以简化代码,而且还能让您以全新的视角审视数据。

在本指南中,我们将深入剖析 reduce 方法的运作原理,并通过 8 个实际应用实例,带您领略它的神奇之处。无论您是 JavaScript 新手还是资深开发者,都能从中学到一些新的东西。

1. 数组求和:简化数字累加

reduce 方法最基本的应用之一便是数组求和。假设我们有一个包含数字的数组 numbers,想要计算它们的总和,可以使用以下代码:

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

在这个例子中,reduce 方法接受两个参数:一个累加器 accumulator 和一个当前值 currentValue。累加器用于存储中间结果,而当前值则代表数组中的下一个元素。reduce 方法会遍历数组中的每个元素,并不断将累加器和当前值相加,最终返回累加器的值。

2. 数组最大值/最小值:轻松找出数组中的王者

reduce 方法还可以轻松找出数组中的最大值或最小值。只需将累加器初始化为数组的第一个元素,然后在遍历数组时,比较累加器和当前值,并更新累加器为较大的/较小的值即可。

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

const min = numbers.reduce((accumulator, currentValue) => Math.min(accumulator, currentValue));
console.log(min); // 输出:1

3. 数组去重:剔除重复元素,留下独一无二

如果您需要从数组中剔除重复元素,reduce 方法也能帮您轻松实现。只需将累加器初始化为空数组,然后在遍历数组时,检查当前值是否已经存在于累加器中。如果不存在,则将其添加到累加器中。

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

4. 对象计数:轻松统计对象属性的出现次数

reduce 方法在对象计数方面也大显身手。假设我们有一个包含多个对象的数组 objects,每个对象都有一个 name 属性。要统计每个 name 属性出现的次数,可以使用以下代码:

const objects = [
  { name: 'John', age: 25 },
  { name: 'Mary', age: 30 },
  { name: 'Bob', age: 28 },
  { name: 'John', age: 32 },
  { name: 'Mary', age: 26 },
];

const nameCounts = objects.reduce((accumulator, currentValue) => {
  const name = currentValue.name;
  accumulator[name] = (accumulator[name] || 0) + 1;
  return accumulator;
}, {});

console.log(nameCounts);
// 输出:{ John: 2, Mary: 2, Bob: 1 }

5. 数组分组:按指定条件将数组元素归类

reduce 方法还可以将数组元素根据指定条件进行分组。假设我们有一个包含学生成绩的数组 scores,每个学生都有一个 name 属性和一个成绩 score 属性。要将学生成绩按分数范围分组,可以使用以下代码:

const scores = [
  { name: 'John', score: 90 },
  { name: 'Mary', score: 80 },
  { name: 'Bob', score: 70 },
  { name: 'Alice', score: 95 },
  { name: 'Tom', score: 85 },
];

const groupedScores = scores.reduce((accumulator, currentValue) => {
  const scoreRange = currentValue.score >= 90 ? 'A' : currentValue.score >= 80 ? 'B' : 'C';
  accumulator[scoreRange] = accumulator[scoreRange] || [];
  accumulator[scoreRange].push(currentValue);
  return accumulator;
}, {});

console.log(groupedScores);
// 输出:{ A: [{ name: 'John', score: 90 }, { name: 'Alice', score: 95 }], B: [{ name: 'Mary', score: 80 }, { name: 'Tom', score: 85 }], C: [{ name: 'Bob', score: 70 }] }

6. 数组扁平化:将多维数组变为一维数组

如果您需要将多维数组扁平化成一维数组,reduce 方法也是您的不二之选。假设我们有一个多维数组 multiArray,可以使用以下代码将其扁平化:

const multiArray = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];

const flatArray = multiArray.reduce((accumulator, currentValue) => accumulator.concat(currentValue), []);
console.log(flatArray); // 输出:[1, 2, 3, 4, 5, 6, 7, 8, 9]

7. 数组转换:轻松将数组元素转换为其他类型

reduce 方法还可以将数组元素转换为其他类型。假设我们有一个包含字符串的数组 strings,想要将它们全部转换为大写,可以使用以下代码:

const strings = ['john', 'mary', 'bob'];

const capitalizedStrings = strings.reduce((accumulator, currentValue) => {
  accumulator.push(currentValue.toUpperCase());
  return accumulator;
}, []);

console.log(capitalizedStrings); // 输出:[ 'JOHN', 'MARY', 'BOB' ]

8. 自定义归约:掌握高级用法,玩转数据处理

reduce 方法的真正强大之处在于它的自定义归约能力。您可以根据自己的需求,定义自己的归约函数,从而实现各种复杂的数据处理任务。

例如,假设我们有一个包含交易记录的数组 transactions,每个交易记录都有一个 amount 属性和一个 type 属性。要计算所有交易的总收入和总支出,可以使用以下代码:

const transactions = [
  { amount: 100, type: 'income' },
  { amount: 200, type: 'expense' },
  { amount: 300, type: 'income' },
  { amount: 400, type: 'expense' },
  { amount: 500, type: 'income' },
];

const totalIncome = transactions.reduce((accumulator, currentValue) => {
  if (currentValue.type === 'income') {
    accumulator += currentValue.amount;
  }
  return accumulator;
}, 0);

const totalExpense = transactions.reduce((accumulator, currentValue) => {
  if (currentValue.type === 'expense') {
    accumulator += currentValue.amount;
  }
  return accumulator;
}, 0);

console.log(`Total Income: ${totalIncome}`); // 输出:Total Income: 900
console.log(`Total Expense: ${totalExpense}`); // 输出:Total Expense: 600

总结:reduce 方法的强大与优雅

通过这 8 个实例,我们领略了 reduce 方法的强大与优雅。它不仅可以简化代码,而且还能让我们以全新的视角审视数据。掌握 reduce 方法,您将成为 JavaScript 编程高手。