icon
reduce-has-been-used-in-many-scenarios-check-it-out

2023年4月29日星期六 下午11:25

原來Array.prototype.reduce很常被使用,來學一下!

When I looked into the source code of some projects, I often see reduce has been used. Which makes feel like I need to know more about it. .reduce is a very versatile array function in JavaScript. The ways of using it could vary depending on the purpose.

Introduction

From MDN, we can get the following definition of reduce:

The reduce() method executes a user-supplied "reducer" callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value.

So basically, the reduce() method takes a user-defined callback as one of the parameters to iterate through the array and passes the return value of each iteration to the next iteration.

Usage

Here we'll have a look at how to use it. The reduce() function takes two parameters (the callback function and the initial value), and the callback function can take up to four parameters and pass from the reduce() function automatically:

// Syntax
Array.prototype.reduce(callbackFn, initialValue);

const callbackFn = (accumulator, currentValue, currentIndex, array) {
  // accumulator: For the 1st iteration, it's the initialValue, for the rest of the iteration, it's the return value of the previous iteration.

  // currentValue: the value of the current element of the iteration.

  // currentIndex: the index of the current iteration.

  // array: the array that reduce() function was called upon. 
}

After knowing how the syntax works, we can have a look at how people use it in real life.

Summation

We know that the reduce() method can loop through an array while keeping a value passed across iterations. And finding the summation is exactly what it can do.

The initial value and the accumulator can be a form a object as well, so we can try it out in this case.
// let say we want to keep track of how many numbers are used.
const nums = [2, 4, 6, 8, 10];

const result = nums.reduce((result, val) => {
  result.count += 1;
  result.sum += val;

  return result;
}, {count: 0, sum: 0});

console.log(result); // {count: 5, sum: 30}
Don't forget to return the value you want to pass to the next iteration.

Max and Min

It's also intuitive that we can use it for finding the maximum and the minimum value among an array.

const nums = [10, 4, 1, 8, 6];

const min = nums.reduce((min, val) => {
  min = val < min ? val : min;

  return min;
}, Number.POSITIVE_INFINITY);

console.log(min); // 2

Piping

A pipe is a function that allows us to connect the functions together, which means passing the output of a function as the input of the next function. From my perspective, piping helps the coding more clean and intuitive when it comes to passing the output of a function as the input of another function.

// Here's we will implement a pipe function
const pipe = (...funcs) => val => {
  return funcs.reduce((value, func) => {
    return func(value);
  }, val);
}

// Use case: let say we're making a addition piping

const add1 = value => value + 1;
const add3 = value => value + 3;
const add5 = value => value + 5;

const addSum = pipe(
  add1,
  add2,
  add5
);

const result = addSum(10)

console.log(result); // 19
Here we used a concept of curried function on the double fat arrow function syntax.

The notes I wrote for building your own compiler with JavaScript, from the raw code input to the result, we can use piping to enhance the readability of the codes.

Reduce vs Map and Filter

These three are all array methods in JavaScript that iterate over an array and perform some sort of computation. Both map() and filter() can only return an array, whereas reduce() can return not only an array but also any data type in JavaScript like a single value or an object.

For me, as long as the operations involve more than just one element in the iteration, I would pick reduce() over map(). Vice versa, if the operation only involves one element in each iteration, I would go for map() or filter().

Reference

  1. DigitalOcean, The JavaScript Reduce Method Explained - https://www.digitalocean.com/community/tutorials/js-finally-understand-reduce
  2. FreeCodeCamp, A guide to the reduce method in JavaScript - https://www.freecodecamp.org/news/reduce-f47a7da511a9
  3. Stack Overflow, what do multiple arrow functions mean in JavaScript - https://stackoverflow.com/questions/32782922/what-do-multiple-arrow-functions-mean-in-javascript