AlgoDaily

Implement Array.reduce

Read at your own pace. Code execution, quizzes, progress tracking, and the AI tutor are available in the interactive view with JavaScript enabled.

Question

In JavaScript there is a built-in method called reduce() that can be used over the Array prototype. What this method does, is that it executes a user-supplied "reducer" callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value.

The first time that the callback is run there is no "return value of the previous calculation". If supplied, an initial value may be used in its place. Otherwise the array element at index 0 is used as the initial value and iteration starts from the next element (index 1 instead of index 0).

The easiest to understand case for reduce() is to return the sum of all the elements in an array:

const array1 = [1, 2, 3, 4];

// 0 + 1 + 2 + 3 + 4
const initialValue = 0;
const sumWithInitial = array1.reduce(
  (previousValue, currentValue) => previousValue + currentValue,
  initialValue
);

console.log(sumWithInitial);
// expected output: 10

Can you implement your own version of this method?

cover

Solution

Solution

Our solution would be a function that recceives 2 arguments: the callback function, and an initial value (optional).

First, we are going to check if we have passed an empty array without an initial value, and if so, return an error:

const argsLength = arguments.length;

if (argsLength === 1 && this.length === 0) {
  throw new Error();
}

Then we are going to define our initial index, and initial result value - based on our argsLength. So, our initial result value will be the initialValue if any supplied, or otherwise it will be the return value of the previous calculation.

let  index  =  argsLength  ===  1  ?  1  :  0;
let  resultValue  =  argsLength  ===  1  ?  this[0] :  initialValue;

Then, in a for loop, we are going to call the callback function with the adequate parameters (current result value, the currently looped array element, its index, and the array itself). The return value of the callback function will be our new result value.

for (let i = index; i < this.length; i += 1) {
  resultValue = callback(resultValue, this[i], i, this);
}

This being said, our final solution would look like this:

Array.prototype.myReduce = function (callback, initialValue) {
  const argsLength = arguments.length;
  //If array is empty and there is no initial value, return an error
  if (argsLength === 1 && this.length === 0) {
    throw new Error();
  }

  let index = argsLength === 1 ? 1 : 0;
  let resultValue = argsLength === 1 ? this[0] : initialValue;

  //Call the callback function for every element and replace the resultValue
  for (let i = index; i < this.length; i += 1) {
    resultValue = callback(resultValue, this[i], i, this);
  }

  return resultValue;
};

One Pager Cheat Sheet

One Pager Cheat Sheet

  • Using the built-in JavaScript methodreduce()you can create a single value from the elements in an array by running a user-supplied "reducer" callback function on each element, optionally passing an initial value first.
  • We created a custom function, myReduce, that takes a callback function and an optional initialValue as arguments, and loops through the array elements by calling the callback with the adequate parameters, returning the final result value.
Open interactive view →