Home » Posts » “reduce” function in JavaScript

“reduce” function in JavaScript

reduce function returns a single value as output by executing a callback function called “reducer” on each element of the array on which it is called upon. It is defined on the prototype of Array class.

Array.prototype.reduce

Result from execution of “reducer” function on one element is given as input to the second one and so on until it reaches the end of the array and return the accumulated result as output.

reduce function can have an optional initial value which if given will be passed as result to the reducer function for the first element, otherwise first element will be considered as a result and reducing will begin from the second element.

Below is a flow chart of reduce flow for an array containing 4 elements.

Reducer flow for an array containing 4 elements.
Reducer flow for an array containing 4 elements

Syntax

reduce(callbackFn, initialValue)
  • callbackFn – Reducer function
    • callbackFn(result, element, index, array)
      • result – Result from the execution of reducer function on the previous element.
      • element – Current element of the array.
      • index – Index of the current element in the array.
      • array – The array on which the reduce function is called upon.
  • initialValue – Value to be treated as result for the first element.

Examples

    const numbers = [1, 2, 3, 4, 5, 6, 7];
    const sum = numbers.reduce((result, x) => result + x);
    console.log(sum);
28
    const numbers = [1, 2, 3, 4, 5, 6, 7];
    const sum = numbers.reduce((result, x) => result + x, -8);
    console.log(sum);
20

Can we write our own “reduce” function?

Yes, it is absolutely possible to write our own “reduce” function. Let’s try to write one.

    Array.prototype.myReduce = function (callbackFn, initialValue) {
        let start = 1;
        let result = this[0];

        if (initialValue !== null && initialValue !== undefined) {
            start = 0;
            result = initialValue;
        }

        for (let i = start; i < this.length; i++) {
            result = callbackFn(result, this[i], i, this);
        }

        return result;
    }

Let’s test our implementation by using it as a filter.

    const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
    const evenNumbers = numbers.myReduce((result, x) => {
        if (x % 2 === 0) {
            result.push(x);
        }

        return result;
    }, []);
    console.log(evenNumbers);
[ 2, 4, 6, 8, 10 ]

Explanation

  1. Define a new function on prototype of Array class. We are doing this because we want our function to be available on arrays rather taking them as argument.
  2. Initialize result based on initial value.
  3. Iterate over the elements and execute the “reducer” function with result passed as an argument. Store the return value of each reducer call in result variable for the next reducer call.
  4. Return the final result value.

References

  1. Mozilla Developer Network (MDN)

Leave a Reply

Your email address will not be published.