Javascript array reduce method

The reduce() method is used to reduce an array to a single value. It takes a callback function as an argument that is executed for each element in the array. The callback function takes two arguments: the accumulator and the current value. The accumulator is the value that is returned after each iteration and is passed on to the next iteration.

Here are a few examples to illustrate how to use reduce() method:

Example 1: Sum of all elements in an array.

In this example, we are using reduce() method to find the sum of all the elements in the array. The 0 argument is the initial value of the accumulator.

 
 const arr = [1, 2, 3, 4, 5];
 const sum = arr.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
 console.log(sum); // Output: 15
 

Example 2: Counting the number of occurrences of an element in an array

In this example, we are using reduce() method to count the number of occurrences of each element in the array. The initial value of the accumulator is an empty object {}. The callback function checks if the currentValue is already present in the accumulator object. If it is, it increments its value by 1, otherwise it initializes its value to 1.

 
 
const arr = ['apple', 'banana', 'apple', 'orange', 'banana', 'mango', 'apple'];
 
const count = arr.reduce((accumulator, currentValue) => {
    if (currentValue in accumulator) {
        accumulator[currentValue]++;
    } else {
        accumulator[currentValue] = 1;
    }
    return accumulator;
}, {});
console.log(count); 
// Output: { apple: 3, banana: 2, orange: 1, mango: 1 }
 
 

Example 3: Flattening an array of arrays

In this example, we are using reduce() method to flatten an array of arrays. The initial value of the accumulator is an empty array []. The callback function concatenates the currentValue array with the accumulator array.

 
 const arr = [[1, 2], [3, 4], [5, 6]];
 
 const flattened = arr.reduce((accumulator, currentValue) => accumulator.concat(currentValue), []);
 
 console.log(flattened); // Output: [1, 2, 3, 4, 5, 6]
 
 

 

Example 4: Finding the maximum value in an array

In this example, we are using reduce() method to find the maximum value in an array. The initial value of the accumulator is 0. The callback function compares the currentValue with the accumulator and returns the greater of the two.

 
const arr = [10, 5, 20, 15, 30];
const max = arr.reduce((accumulator, currentValue) => {
    if (currentValue > accumulator) {
        return currentValue;
    } else {
        return accumulator;
    }
}, 0);
console.log(max); // Output: 30