reduce案例

wen java案例 1

本文目录导读:

reduce案例

  1. 基础语法
  2. 案例 1:数组求和(最基础)
  3. 案例 2:数组扁平化(降维)
  4. 案例 3:对象分组 / 计数
  5. 案例 4:数组去重
  6. 案例 5:按属性分组(高级用法)
  7. 案例 6:扁平化并排序
  8. 案例 7:数组转对象
  9. 案例 8:链式操作(组合多个 reduce)
  10. 案例 9:使用初始值来避免空数组错误
  11. 案例 10:复杂业务逻辑

reduce() 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值,它非常强大,是函数式编程的核心工具。

基础语法

array.reduce((accumulator, currentValue, currentIndex, array) => {
  // 返回新的累加器值
}, initialValue);

以下是几个典型场景的案例:


案例 1:数组求和(最基础)

const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((acc, curr) => acc + curr, 0);
console.log(sum); // 15

其他类似:

// 求最大值
const max = numbers.reduce((acc, curr) => Math.max(acc, curr), -Infinity);
console.log(max); // 5
// 求乘积(累乘)
const product = numbers.reduce((acc, curr) => acc * curr, 1);
console.log(product); // 120

案例 2:数组扁平化(降维)

const nestedArray = [[1, 2], [3, 4], [5, 6]];
const flattened = nestedArray.reduce((acc, curr) => acc.concat(curr), []);
console.log(flattened); // [1, 2, 3, 4, 5, 6]
// 或者用展开运算符更简洁
const flattened2 = nestedArray.reduce((acc, curr) => [...acc, ...curr], []);
console.log(flattened2); // [1, 2, 3, 4, 5, 6]

案例 3:对象分组 / 计数

const fruits = ['apple', 'banana', 'orange', 'apple', 'orange', 'apple'];
const count = fruits.reduce((acc, fruit) => {
  acc[fruit] = (acc[fruit] || 0) + 1;
  return acc;
}, {});
console.log(count); 
// { apple: 3, banana: 1, orange: 2 }

案例 4:数组去重

const numbers = [1, 2, 2, 3, 4, 4, 5];
const unique = numbers.reduce((acc, curr) => {
  if (!acc.includes(curr)) {
    acc.push(curr);
  }
  return acc;
}, []);
console.log(unique); // [1, 2, 3, 4, 5]

案例 5:按属性分组(高级用法)

const people = [
  { name: 'Alice', age: 25, department: 'Engineering' },
  { name: 'Bob', age: 30, department: 'Design' },
  { name: 'Charlie', age: 35, department: 'Engineering' },
  { name: 'David', age: 28, department: 'Design' }
];
const groupedByDepartment = people.reduce((acc, person) => {
  const dept = person.department;
  if (!acc[dept]) {
    acc[dept] = [];
  }
  acc[dept].push(person);
  return acc;
}, {});
console.log(groupedByDepartment);
// {
//   Engineering: [
//     { name: 'Alice', age: 25, department: 'Engineering' },
//     { name: 'Charlie', age: 35, department: 'Engineering' }
//   ],
//   Design: [
//     { name: 'Bob', age: 30, department: 'Design' },
//     { name: 'David', age: 28, department: 'Design' }
//   ]
// }

案例 6:扁平化并排序

const orders = [
  { product: 'Laptop', price: 1000, quantity: 2 },
  { product: 'Mouse', price: 25, quantity: 5 },
  { product: 'Keyboard', price: 75, quantity: 3 }
];
// 计算总价
const totalCost = orders.reduce((acc, item) => {
  return acc + (item.price * item.quantity);
}, 0);
console.log(totalCost); // (1000*2) + (25*5) + (75*3) = 2000 + 125 + 225 = 2350

案例 7:数组转对象

const keyValuePairs = [
  ['name', 'John'],
  ['age', 30],
  ['city', 'New York']
];
const object = keyValuePairs.reduce((acc, [key, value]) => {
  acc[key] = value;
  return acc;
}, {});
console.log(object); // { name: 'John', age: 30, city: 'New York' }

案例 8:链式操作(组合多个 reduce)

// 统计一段文本中每个单词的出现次数
const text = "the quick brown fox jumps over the lazy dog the fox";
const wordCount = text
  .toLowerCase()
  .split(' ')
  .reduce((acc, word) => {
    acc[word] = (acc[word] || 0) + 1;
    return acc;
  }, {});
console.log(wordCount);
// { the: 3, quick: 1, brown: 1, fox: 2, jumps: 1, over: 1, lazy: 1, dog: 1 }

案例 9:使用初始值来避免空数组错误

const emptyArray = [];
// 如果没有初始值,空数组会报错
try {
  emptyArray.reduce((acc, curr) => acc + curr);
} catch (error) {
  console.log('Error:', error.message); // Error: Reduce of empty array with no initial value
}
// 提供初始值就不会有问题
const result = emptyArray.reduce((acc, curr) => acc + curr, 0);
console.log(result); // 0

案例 10:复杂业务逻辑

// 根据订单状态计算不同金额
const transactions = [
  { id: 1, type: 'income', amount: 1000, category: 'salary' },
  { id: 2, type: 'expense', amount: 500, category: 'rent' },
  { id: 3, type: 'income', amount: 200, category: 'freelance' },
  { id: 4, type: 'expense', amount: 150, category: 'food' }
];
const summary = transactions.reduce((acc, transaction) => {
  if (transaction.type === 'income') {
    acc.totalIncome += transaction.amount;
    acc.byCategory[transaction.category] = 
      (acc.byCategory[transaction.category] || 0) + transaction.amount;
  } else {
    acc.totalExpense += transaction.amount;
  }
  acc.balance = acc.totalIncome - acc.totalExpense;
  return acc;
}, { totalIncome: 0, totalExpense: 0, balance: 0, byCategory: {} });
console.log(summary);
// {
//   totalIncome: 1200,
//   totalExpense: 650,
//   balance: 550,
//   byCategory: { salary: 1000, freelance: 200 }
// }

reduce 的核心优势在于能够将数组转换为任何你想要的数据结构(数字、字符串、对象、嵌套数组等),同时保证代码简洁、功能强大。

常见用途:

  • 求和、求积、找最值
  • 数组转对象、分组统计
  • 计数、去重、扁平化(降维)
  • 复杂数据聚合

在开发中,如果你发现自己写了多个 map/filter 嵌套循环做累加操作,通常可以改用 reduce 让代码更优雅。

抱歉,评论功能暂时关闭!