Basic usage and strange usage of array method reduce

Array.prototype.reduceis one of the JavaScript array methods that accumulates the individual values ​​of an array, reducing them to a single value. Here are some basic uses and some that may be considered strange or less common:

Basic usage:

  1. Array sum:
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((acc, curr) => acc + curr, 0);
console.log(sum); // 输出 15
  1. Find the maximum value:
const values = [10, 30, 50, 20, 40];
const max = values.reduce((acc, curr) => Math.max(acc, curr), -Infinity);
console.log(max); // 输出 50
  1. Array deduplication:
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]

Weird usage:

  1. Array tiling:
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. Convert object array to object:
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. Condition statistics:
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}

These examples show some basic and creative uses of reduce. Because reduce has great flexibility, it can be applied to many scenarios.

Guess you like

Origin blog.csdn.net/m0_46672781/article/details/134596513