js中reduce方法的常用应用场景

reduce() 方法可以用来迭代数组并且执行一个回调函数,将数组中的元素聚合成一个单独的值。它可以被用于一系列的操作,如累加求和,计算平均值和查找最大值或最小值等。以下是reduce() 方法的几个应用场景和相应的示例:

  1. 求和或求积:

可以使用reduce方法来对数组中的所有元素进行求和或求积。

let numbers = [1, 2, 3, 4];
let sum = numbers.reduce((previous, current) => previous + current, 0);
console.log(sum); // 结果为10

let product = numbers.reduce((previous, current) => previous * current, 1);
console.log(product); // 结果为24
  1. 找出数组中的最大值
const numbers = [10, 20, 30, 40];
const max = numbers.reduce((accumulator, currentValue) => Math.max(accumulator, currentValue));
console.log(max); // Output: 40
  1. 计算平均值
const numbers = [10, 20, 30, 40];
const average = numbers.reduce((accumulator, currentValue, index, array) => {
  accumulator += currentValue;
  if (index === array.length - 1) {
    return accumulator / array.length;
  } else {
    return accumulator;
  }
});
console.log(average); // Output: 25
  1. 计数:

可以使用reduce方法来计算数组中特定元素的出现次数。

let animals = ['dog', 'cat', 'dog', 'cat', 'bird', 'cat'];
let count = animals.reduce((previous, animal) => {
  if(animal in previous) {
    previous[animal]++;
  } else {
    previous[animal] = 1;
  }
  return previous;
}, {});
console.log(count); // 结果为 { dog: 2, cat: 3, bird: 1 }
const str = 'hello world';
const charCount = str.split('').reduce((result, char) => {
  if (!result[char]) {
    result[char] = 1;
  } else {
    result[char]++;
  }
  return result;
}, {});
console.log(charCount); // Output: { h: 1, e: 1, l: 3, o: 2, ' ': 1, w: 1, r: 1, d: 1 }
  1. 筛选:

可以使用reduce方法来筛选出满足条件的元素。

let numbers = [1, 2, 3, 4, 5, 6];
let evenNumbers = numbers.reduce((previous, number) => {
  if(number % 2 == 0) {
    previous.push(number);
  }
  return previous;
}, []);
console.log(evenNumbers); // 结果为 [2, 4, 6]
// 筛选出所有年龄大于 20 岁的人
const people = [
  { name: 'Amy', age: 23 },
  { name: 'Bob', age: 18 },
  { name: 'Charlie', age: 27 },
  { name: 'David', age: 30 },
  { name: 'Emily', age: 21 }
];
const result = people.reduce((accumulator, currentValue) => {
  if (currentValue.age > 20) {
    accumulator.push(currentValue);
  }
  return accumulator;
}, []);
console.log(result); // Output: [{ name: 'Amy', age: 23 }, { name: 'Charlie', age: 27 }, { name: 'David', age: 30 }, { name: 'Emily', age: 21 }]

// 筛选出所有姓氏为“张”的人的名字和年龄
const people = [
  { name: '张三', age: 23 },
  { name: '李四', age: 18 },
  { name: '张五', age: 27 },
  { name: '王六', age: 30 },
  { name: '张七', age: 21 }
];
const result = people.reduce((accumulator, currentValue) => {
  if (currentValue.name.startsWith('张')) {
    accumulator.push({ name: currentValue.name, age: currentValue.age });
  }
  return accumulator;
}, []);
console.log(result); // Output: [{ name: '张三', age: 23 }, { name: '张五', age: 27 }, { name: '张七', age: 21 }]


// 将数组对象按照条件筛选成多个数组对象
const people = [
  { name: 'Amy', country: 'USA' },
  { name: 'Bob', country: 'Canada' },
  { name: 'Charlie', country: 'USA' },
  { name: 'David', country: 'Canada' },
  { name: 'Emily', country: 'USA' }
];
const result = people.reduce((accumulator, currentValue) => {
  const country = currentValue.country;
  if (!accumulator[country]) {
    accumulator[country] = [];
  }
  accumulator[country].push(currentValue);
  return accumulator;
}, {});
console.log(result);
/*{
  USA: [
    { name: 'Amy', country: 'USA' },
    { name: 'Charlie', country: 'USA' },
    { name: 'Emily', country: 'USA' }
  ],
  Canada: [
    { name: 'Bob', country: 'Canada' },
    { name: 'David', country: 'Canada' }
  ]
}
*/

  1. 扁平化数组:

可以使用reduce方法来将多维数组变为一维。

let arrays = [[1, 2, 3], [4, 5], [6]];
let flatten = arrays.reduce((previous, current) => [...previous, ...current], []);
console.log(flatten); // 结果为 [1, 2, 3, 4, 5, 6]

总的来说,任何需要对数组中的所有元素进行操作并得到一个结果的场景都可以考虑使用reduce方法。

你可能感兴趣的:(常用的数据处理,javascript,前端,vue.js)