Community

Start a Thread


Notifications
Subscribe You’re not receiving notifications from this thread.

Implement Array Reduce (Main Thread)

Here is the interview question prompt, presented for reference.

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](https://storage.googleapis.com/algodailyrandomassets/curriculum/frontend/interview-questions/implement-array-reduce.jpg)

You can see the full challenge with visuals at this link.

Challenges • Asked over 3 years ago by Jake from AlgoDaily

Jake from AlgoDaily Commented on Jun 04, 2022:

This is the main discussion thread generated for Implement Array Reduce (Main Thread).