reduce函数使用汇总

195 阅读1分钟

reduce 函数在处理对象数组时非常有用,它可以帮助你执行各种数据聚合和转换操作。

1. 聚合属性值

将对象数组中某个属性的所有值聚合起来,比如求和、合并数组等。

const products = [
  { name: 'Apple', price: 10, category: 'Fruit' },
  { name: 'Banana', price: 5, category: 'Fruit' },
  { name: 'Carrot', price: 3, category: 'Vegetable' }
];

// 计算总价格
const totalCost = products.reduce((total, product) => total + product.price, 0);
console.log(totalCost); // 输出: 18

2. 按属性分组

根据对象数组中某个属性的值将对象分组。

// 按类别分组
const groupedByCategory = products.reduce((acc, product) => {
  (acc[product.category] = acc[product.category] || []).push(product);
  return acc;
}, {});

console.log(groupedByCategory);
// 输出:
// {
//   Fruit: [
//     { name: 'Apple', price: 10, category: 'Fruit' },
//     { name: 'Banana', price: 5, category: 'Fruit' }
//   ],
//   Vegetable: [
//     { name: 'Carrot', price: 3, category: 'Vegetable' }
//   ]
// }

3. 构建索引

创建一个索引,其中键是对象数组中某个属性的值,值是对应的对象。

const indexedByName = products.reduce((acc, product) => {
  acc[product.name] = product;
  return acc;
}, {});

console.log(indexedByName);
// 输出:
// {
//   Apple: { name: 'Apple', price: 10, category: 'Fruit' },
//   Banana: { name: 'Banana', price: 5, category: 'Fruit' },
//   Carrot: { name: 'Carrot', price: 3, category: 'Vegetable' }
// }

4. 提取属性数组

从对象数组中提取特定属性的值,形成一个新数组。

// 提取所有产品名称
const names = products.reduce((acc, product) => {
  acc.push(product.name);
  return acc;
}, []);

console.log(names); // 输出: ['Apple', 'Banana', 'Carrot']

5. 过滤并聚合

过滤对象数组,然后聚合剩余对象的某个属性。

// 过滤出价格大于5的产品,并计算它们的总价格
const totalExpensive = products.reduce((total, product) => {
  if (product.price > 5) {
    return total + product.price;
  }
  return total;
}, 0);

console.log(totalExpensive); // 输出: 10

6. 复杂转换

执行更复杂的转换,比如根据多个条件创建新对象。

// 为每个产品添加一个描述字段
const productsWithDescription = products.reduce((acc, product) => {
  const description = `${product.name} costs $${product.price}`;
  acc.push({ ...product, description });
  return acc;
}, []);

console.log(productsWithDescription);
// 输出:
// [
//   { name: 'Apple', price: 10, category: 'Fruit', description: 'Apple costs $10' },
//   { name: 'Banana', price: 5, category: 'Fruit', description: 'Banana costs $5' },
//   { name: 'Carrot', price: 3, category: 'Vegetable', description: 'Carrot costs $3' }
// ]