How to use reduce() function in Javascript

The reduce() function is a powerful tool in JavaScript that allows you to iterate over an array and reduce the values to a single output. It can be used to perform a variety of tasks, such as calculating the sum of an array of numbers, finding the maximum value in an array, or even flattening an array of arrays.

To use the reduce() function, you need to pass it a callback function that will be called for each element in the array. This callback function should take two arguments: the previous value and the current value. The reduce() function will then apply this callback function to each element in the array, starting from the left, and return the final result.

Here is an example of using the reduce() function to calculate the sum of an array of numbers:


const numbers = [1, 2, 3, 4, 5];

const sum = numbers.reduce((prev, curr) => prev + curr);

console.log(sum); // 15

In this example, the callback function passed to reduce() simply adds the previous value to the current value and returns the result. The reduce() function starts by setting the previous value to the first element in the array (1) and the current value to the second element (2). It then applies the callback function to these values and sets the previous value to the result (3). It continues this process until it reaches the end of the array, at which point it returns the final result (15).

You can also specify an initial value as the second argument to the reduce() function. This initial value will be used as the previous value in the first iteration. For example:


const numbers = [1, 2, 3, 4, 5];

const sum = numbers.reduce((prev, curr) => prev + curr, 10);

console.log(sum); // 25

In this case, the reduce() function will start by setting the previous value to the initial value of 10 and the current value to the first element in the array (1). It will then apply the callback function to these values and set the previous value to the result (11). It will continue this process until it reaches the end of the array, at which point it will return the final result (25).

The reduce() function can also be used to perform more complex tasks, such as finding the maximum value in an array or flattening an array of arrays. For example:


const numbers = [1, 2, 3, 4, 5];

const max = numbers.reduce((prev, curr) => Math.max(prev, curr));

console.log(max); // 5

const nestedArray = [[1, 2], [3, 4], [5, 6]];

const flatten = nestedArray.reduce((prev, curr) => prev.concat(curr), []);

console.log(flatten); // [1, 2, 3, 4, 5, 6]

In the first example, the callback function passed to reduce() uses the Math.max() function to find the maximum value in the array. In the second example, the callback function uses the concat() method to flatten the array.