0% found this document useful (0 votes)
4 views

Array.prototype.reduce _ JavaScript Interview Questions with Solutions

The document discusses the implementation of Array.prototype.reduce through a custom method called Array.prototype.myReduce, highlighting its nuances and edge cases. It emphasizes the importance of understanding how the reducer callback works, including parameters passed and behavior with empty or mutated arrays. Additionally, it provides examples and notes on potential pitfalls when using the reduce function.

Uploaded by

Parth Tiwari
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Array.prototype.reduce _ JavaScript Interview Questions with Solutions

The document discusses the implementation of Array.prototype.reduce through a custom method called Array.prototype.myReduce, highlighting its nuances and edge cases. It emphasizes the importance of understanding how the reducer callback works, including parameters passed and behavior with empty or mutated arrays. Additionally, it provides examples and notes on potential pitfalls when using the reduce function.

Uploaded by

Parth Tiwari
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Coding and submission is not supported on mobile devices.

Use a wider
screen to practice solving this question within the editor.
Array.prototype.reduce
Interviews
Easy 15 mins 4.08k done Hide solution

Array.prototype.reduce is a way of "reducing" elements in an array by calling a This question might seem easy on first glance, but the nuances make the
"reducer" callback function on each element of the array in order, passing in the question trickier than it seems on the surface. Knowing the nuances differentiates
return value from the calculation on the preceding element. The final result of senior candidates and gives you bonus points. Are you aware that:
running the reducer across all elements of the array is a single value.
The reducer callback is passed the currentIndex and array as the third and
Implement Array.prototype.reduce . To avoid overwriting the actual fourth argument respectively?
Array.prototype.reduce which is being used by the autograder, we shall instead If there is no initial value supplied
GFE 75 to 2/70
the reduce function, the arrayMarkelement
completeat
implement it as Array.prototype.myReduce . index 0 is used and the iteration starts from the next element (index 1 instead
of index 0).
Examples
Solution
[1, 2, 3].myReduce((prev, curr) => prev + curr, 0); // 6 The rest of the implementation is straightforward with these nuances taken into
[1, 2, 3].myReduce((prev, curr) => prev + curr, 4); // 10
account. As we loop through the array (via this ), call the callback on each array
element with the following parameters: acc , element , index , and this . The
returned value will become the new acc to be passed to the next call of the
Notes callbackFn .

There are some nuances regarding how the Array.prototype.reduce function JavaScript TypeScript
works and what values are being passed to the reducer callback. You are
recommended to read the specification for Array.prototype.reduce on MDN Docs
before attempting. 1
2
/**
* @template T, U
3 * @param {(previousValue: U, currentValue: T, currentIndex: number, array:

Companies 4
5
* @param {U} [initialValue]
* @return {Array<U>}

Amazon Apple ByteDance 6 */


7 Array.prototype.myReduce = function (callbackFn, initialValue) {
8 const noInitialValue = initialValue === undefined;
9 const len = this.length; Elements appended to the array after the call to reduce begins will not be
10
11 if (noInitialValue && len === 0) {
visited by the callback.
12 throw new TypeError('Reduce of empty array with no initial value'); If existing elements of the array are changed, their value as passed to the
13 } callback will be the value at the time reduce visits them.
14
Elements that are deleted after the call to reduce begins and before being
visited are not visited.
15 let acc = noInitialValue ? this[0] : initialValue;
16 let startingIndex = noInitialValue ? 1 : 0;
17
18
19
for (let k = startingIndex; k < len; k++) {
if (Object.hasOwn(this, k)) { One-liner Solution
20 acc = callbackFn(acc, this[k], k, this);
21 } You can cheat the autograder by doing this:
22 }
23
24 return acc;
25 }; Array.prototype.myReduce = Array.prototype.reduce;

Edge Cases Spec Solution


Empty array, with and without the initialValue argument. Here's a solution that is based off the Array.prototype.reduce ECMAScript
Single-value array, with and without the initialValue argument. specification.
Passing the index and array to the reducer callback.
Sparse arrays, e.g. [1, 2, , 4] . The empty values should be ignored while
traversing the array. 1 Array.prototype.myReduce = function (callbackFn, initialValue) {
2 const len = this.length;

Notes
3
4 if (
5 typeof callbackFn !== 'function' ||

Mutating the array in the reduce callback is a bad idea and can cause unintended 6 !callbackFn.call ||

consequences. It is a positive signal to mention that mutation of the array within 7 !callbackFn.apply

the callback is possible. The provided solution follows the TC39 specification for 8
9
) {
throw new TypeError(`${callbackFn} is not a function`);
array mutation scenarios: 10 }
11
The range of elements processed by reduce is set before the first callback is 12 if (len === 0 && initialValue === undefined) {
called. 13 throw new TypeError('Reduce of empty array with no initial value');
14 }
15
16 let k = 0;
17 let accumulator = undefined;
18
19 if (initialValue !== undefined) {
20 accumulator = initialValue;
21 } else {
22 let kPresent = false;
23 while (!kPresent && k < len) {
24 // Ignore index if value is not defined for index (e.g. in sparse arr
25 kPresent = Object.hasOwn(this, k);
26 if (kPresent) {
27 accumulator = this[k];
28 }
29 k = k + 1;
30 }
31
32 if (!kPresent) {
33 throw new TypeError('Reduce of empty array with no initial value');
34 }
35 }
36
37 while (k < len) {
38 const kPresent = Object.hasOwn(this, k);
39 if (kPresent) {
40 const kValue = this[k];
41 accumulator = callbackFn(accumulator, kValue, k, this);
42 }
43 k = k + 1;
44 }
45
46 return accumulator;
47 };

Resources
Array.prototype.reduce | MDN
Array.prototype.reduce ECMAScript specification

You might also like