数组方法reduce的基础用法和奇怪的用法

Array.prototype.reduce 是 JavaScript 数组方法之一,用于累积数组的各个值,将其简化为单个值。下面是一些基础用法和一些可能被认为奇怪或不太常见的用法:

基础用法:

  1. 数组求和:
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((acc, curr) => acc + curr, 0);
console.log(sum); // 输出 15
  1. 查找最大值:
const values = [10, 30, 50, 20, 40];
const max = values.reduce((acc, curr) => Math.max(acc, curr), -Infinity);
console.log(max); // 输出 50
  1. 数组去重:
const duplicates = [1, 2, 2, 3, 4, 4, 5];
const uniqueValues = duplicates.reduce((acc, curr) => {
    
    
  if (!acc.includes(curr)) {
    
    
    acc.push(curr);
  }
  return acc;
}, []);
console.log(uniqueValues); // 输出 [1, 2, 3, 4, 5]

奇怪的用法:

  1. 数组平铺:
const nestedArray = [[1, 2], [3, 4], [5, 6]];
const flatArray = nestedArray.reduce((acc, curr) => acc.concat(curr), []);
console.log(flatArray); // 输出 [1, 2, 3, 4, 5, 6]
  1. 对象数组转对象:
const people = [
  {
    
     id: 1, name: 'John' },
  {
    
     id: 2, name: 'Jane' },
  {
    
     id: 3, name: 'Doe' },
];
const peopleObject = people.reduce((acc, person) => {
    
    
  acc[person.id] = person.name;
  return acc;
}, {
    
    });
console.log(peopleObject); // 输出 {1: 'John', 2: 'Jane', 3: 'Doe'}
  1. 条件统计:
const numbers = [1, 2, 3, 4, 5];
const countEvenOdd = numbers.reduce(
  (acc, curr) => {
    
    
    curr % 2 === 0 ? acc.even++ : acc.odd++;
    return acc;
  },
  {
    
     even: 0, odd: 0 }
);
console.log(countEvenOdd); // 输出 {even: 2, odd: 3}

这些示例展示了 reduce 的一些基础和创造性的用法。由于 reduce 具有强大的灵活性,它可以应用于许多场景。

猜你喜欢

转载自blog.csdn.net/m0_46672781/article/details/134596513
今日推荐