javascript reduce mdn

JavaScript Reduce MDN

JavaScript reduce() is a method that allows you to reduce an array to a single value. You can use this method to perform several operations on an array such as summing up all the elements in the array, finding the maximum or minimum value in the array, etc.

The syntax of the reduce() method is as follows:


arr.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])
  • callback - A function that is called for every element in the array. It takes four arguments (accumulator, currentValue, index, array) and returns the updated accumulator value.
  • accumulator - The initial value or the previously returned value of the accumulator.
  • currentValue - The current element being processed in the array.
  • index (optional) - The index of the current element being processed in the array.
  • array (optional) - The array reduce() was called upon.
  • initialValue (optional) - The initial value of the accumulator.

Let's take an example to understand the reduce() method:


let arr = [1, 2, 3, 4, 5];

let sum = arr.reduce((accumulator, currentValue) => {
  return accumulator + currentValue;
});

console.log(sum); // Output: 15

In this example, we are using reduce() method to calculate the sum of all the elements in an array. Initially, the accumulator value is set to 0 and the currentValue is the first element of the array. The callback function is executed for each element of the array and the accumulator value is updated every time by adding the currentValue to it. Finally, the sum of all elements is returned and stored in the sum variable.

Another example would be to find the maximum value in an array:


let arr = [1, 2, 3, 4, 5];

let max = arr.reduce((accumulator, currentValue) => {
  return Math.max(accumulator, currentValue);
});

console.log(max); // Output: 5

In this example, we are using reduce() method to find the maximum value in an array. Initially, the accumulator value is set to the first element of the array and the currentValue is the second element of the array. The Math.max() function is used to compare the accumulator and currentValue values and returns the maximum value, which is then stored in the accumulator variable. The callback function is executed for each element of the array and the maximum value is returned and stored in the max variable.

Overall, the reduce() method is a powerful method that can be used to perform various operations on arrays. It can be used to simplify complex code and make it more readable.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe