DEV Community

Muhammad Rizwan Ashiq
Muhammad Rizwan Ashiq

Posted on

Array.reduce() Method

What is Reduce Method?

The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in a single output value.

Syntax

Here's the syntax for using reduce():

const reducedValue = arr.reduce(
    (accumulator, currentValue, currentIndex, array) => {
        // Return the new value of the accumulator
    },
    initialValue
);
Enter fullscreen mode Exit fullscreen mode

The callback function is called for each element in the array and takes the following arguments:

  • accumulator: the accumulator accumulates the callback's return values. It is the accumulated value previously returned in the last invocation of the callback, or initialValue, if supplied (see below).
  • currentValue: the current element being processed in the array.
  • currentIndex (optional): the index of the current element being processed in the array.
  • array (optional): the array reduce() was called upon.
  • initialValue (optional): a value to use as the first argument to the first call of the callback. If no initial value is supplied, the first element in the array will be used as the initial accumulator value and skipped as currentValue. Calling reduce() on an empty array without an initial value will throw a TypeError.

The reduce() method calls the callback function once for each element present in the array, excluding holes in the array, and it persists the return value of the callback function. The first time the callback is called, the accumulator and currentValue can be one of two values. If initialValue is provided in the call to reduce(), then accumulator will be equal to initialValue and currentValue will be equal to the first value in the array. If no initialValue was provided, then accumulator will be equal to the first value in the array and currentValue will be equal to the second.

Here's an example of how to use reduce() to sum all the numbers in an array:

const numbers = [1, 2, 3];

const sum = numbers.reduce(function (accumulator, currentValue) {
    return accumulator + currentValue;
}, 0);

console.log(sum); // prints 6
Enter fullscreen mode Exit fullscreen mode

In the example above, the callback function is an anonymous function that takes two arguments, accumulator and currentValue, and returns the sum of the two values. The reduce() method calls this function for each element in the numbers array. The first time the callback is called, accumulator is equal to 0 and currentValue is equal to 1. The second time the callback is called, accumulator is equal to the return value of the first call to the callback, which is 1, and currentValue is equal to 2. The reduce() method continues calling the callback function until all the elements in the array have been processed. The return value of the reduce() method is equal to the return value of the last call to the callback function.

You can also use an arrow function as the callback function, like this:

const numbers = [1, 2, 3];

const sum = numbers.reduce(
    (accumulator, currentValue) => accumulator + currentValue,
    0
);

console.log(sum); // prints 6
Enter fullscreen mode Exit fullscreen mode

image

The reduce() method can also be used to flatten an array of arrays into a single array. Here's an example:

const flattened = [
    [0, 1],
    [2, 3],
    [4, 5],
].reduce((accumulator, currentValue) => accumulator.concat(currentValue), []);

console.log(flattened); 
// prints [0, 1, 2, 3, 4, 5]
Enter fullscreen mode Exit fullscreen mode

Examples

Count the students who passed

const students = [
    { name: "John", score: 6.4 },
    { name: "Maria", score: 8.2 },
    { name: "Peter", score: 9.8 },
    { name: "Ann", score: 9.2 },
];

const passed = students.reduce((acc, curr) => {
    if (curr.score >= 7) {
        acc++;
    }
    return acc;
}, 0);

console.log(passed); // prints 3
Enter fullscreen mode Exit fullscreen mode

Grouping objects

const students = [
    { name: "John", score: 6.4 },
    { name: "Maria", score: 8.2 },
    { name: "Peter", score: 9.8 },
    { name: "Ann", score: 9.2 },
];

const groupByScore = students.reduce((acc, curr) => {
    const key = Math.floor(curr.score);
    if (!acc[key]) {
        acc[key] = [];
    }
    acc[key].push(curr);
    return acc;
}, {});

console.log(groupByScore);
// prints
// {
//   6: [
//     { name: 'John', score: 6.4 }
//   ],
//   8: [
//     { name: 'Maria', score: 8.2 }
//   ],
//   9: [
//     { name: 'Peter', score: 9.8 },
//     { name: 'Ann', score: 9.2 }
//   ]
// }
Enter fullscreen mode Exit fullscreen mode

Reduce Right

The reduceRight() method works exactly like reduce(), except it applies the callback function from right to left.

Here's an example of how to use reduceRight() to sum all the numbers in an array:

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

const sum = numbers.reduceRight(function (accumulator, currentValue) {
    return accumulator + currentValue;
}, 0);

console.log(sum); // prints 55
Enter fullscreen mode Exit fullscreen mode

Reduce vs. For Loop

The reduce() method is often used to replace a for loop. Here's an example of how to use a for loop to sum all the numbers in an array:

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

let sum = 0;

for (let i = 0; i < numbers.length; i++) {
    sum += numbers[i];
}

console.log(sum); // prints 55
Enter fullscreen mode Exit fullscreen mode

Here's the same example using reduce():

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

const sum = numbers.reduce(
    (accumulator, currentValue) => accumulator + currentValue,
    0
);

console.log(sum); // prints 55
Enter fullscreen mode Exit fullscreen mode

Reduce vs. For Each

The reduce() method is often used to replace a forEach() loop. Here's an example of how to use a forEach() loop to sum all the numbers in an array:

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

let sum = 0;

numbers.forEach(function (number) {
    sum += number;
});

console.log(sum); // prints 55
Enter fullscreen mode Exit fullscreen mode

Here's the same example using reduce():

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

const sum = numbers.reduce(
    (accumulator, currentValue) => accumulator + currentValue,
    0
);

console.log(sum); // prints 55
Enter fullscreen mode Exit fullscreen mode

Reduce vs. Map

The reduce() method is often used to replace a map() loop. Here's an example of how to use a map() loop to sum all the numbers in an array:

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

const doubled = numbers.map(function (number) {
    return number * 2;
});

console.log(doubled); // prints [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
Enter fullscreen mode Exit fullscreen mode

Here's the same example using reduce():

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

const doubled = numbers.reduce((accumulator, currentValue) => {
    accumulator.push(currentValue * 2);
    return accumulator;
}, []);

console.log(doubled); // prints [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
Enter fullscreen mode Exit fullscreen mode

Reduce vs. Filter

The reduce() method is often used to replace a filter() loop. Here's an example of how to use a filter() loop to sum all the numbers in an array:

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

const evens = numbers.filter(function (number) {
    return number % 2 === 0;
});

console.log(evens); // prints [2, 4, 6, 8, 10]
Enter fullscreen mode Exit fullscreen mode

Here's the same example using reduce():

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

const evens = numbers.reduce((accumulator, currentValue) => {
    if (currentValue % 2 === 0) {
        accumulator.push(currentValue);
    }
    return accumulator;
}, []);

console.log(evens); // prints [2, 4, 6, 8, 10]
Enter fullscreen mode Exit fullscreen mode

Reduce vs. Find

The reduce() method is often used to replace a find() loop. Here's an example of how to use a find() loop to sum all the numbers in an array:

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

const found = numbers.find(function (number) {
    return number > 5;
});

console.log(found); // prints 6
Enter fullscreen mode Exit fullscreen mode

Here's the same example using reduce():

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

const found = numbers.reduce((accumulator, currentValue) => {
    if (currentValue > 5) {
        accumulator = currentValue;
    }
    return accumulator;
}, 0);

console.log(found); // prints 6
Enter fullscreen mode Exit fullscreen mode

When to use Reduce

Reduce is not a method that you will use every day, but it is a very useful method to know about. It is a great tool to have in your JavaScript toolbox. When you need to use it, you will be glad you know how to use it.

To honestly, I don't use it very often. I prefer to use forEach() loops, map() loops, filter() loops, and find() loops. I only use reduce() when I need to flatten an array of arrays into a single array, or when I need to sum all the numbers in an array.

If you want to learn more about the reduce() method, check out the MDN documentation.

Conclusion

The reduce() method is a powerful tool for working with arrays. It can be used to sum all the numbers in an array, flatten an array of arrays into a single array, and much more. It can also be used to replace for loops, forEach() loops, map() loops, filter() loops, and find() loops. The reduce() method is a great tool to have in your JavaScript toolbox. I hope this article has helped you understand how to use the reduce() method.

Top comments (0)