Alan Mathew Alan Mathew - 29 days ago 7
Javascript Question

JavaScript -- Unable to understand Array.Map & Array.reduce

I have been working on a problem on FCC (Free code camp) which requires to scan a 2D array and find largest element from each 1D array and put the result into a 1D array. I came across this solution on GitHub was unable to understand it.

function largestOfFour(arr) {
return arr.map(function(group){
return group.reduce(function(prev, current) {
return (current > prev) ? current : prev;
}, 0);
});
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);


OUTPUT IS [5, 27, 39, 1001]



My console.log(arr) gave me: 4,5,1,3,13,27,18,26,32,35,37,39,1000,1001,857,1


  1. How did that 2D array get converted to 1D array when passed as a function parameter?



My console.log(group) gave me: 4,5,1,3 (first time), 13,27,18,26 (second time), 32, 35, 37, 39 (third time) and 1000, 1001, 857, 1 (fourth time).


  1. How was the anonymous function able to take the parameter group as the individual 1D arrays inside the 2D.



Can someone please help.

Answer

When you use Array.map it will process each element within the array for example.

[1, 2, 3, 4].map(function (item) { return item; } ); 

Will just return a new array with [1, 2, 3, 4], but say we double each value we could do it like this.

[1, 2, 3, 4].map(function (item) { return 2 * item; });

Which returns [2, 4, 6, 8] back.

So in your example you have a 2 dimensional array. The Array.map works on the first level. So in each iteration the group is

  • 1st -> [4, 5, 1, 3]
  • 2nd -> [13, 27, 18, 26]
  • 3rd -> [32, 35, 37, 39]
  • 4th -> [1000, 1001, 857, 1]

So the 1st to 4th will then be passed into the Array.reduce function. Reduce just returns a single value based on the array passed in, or better put

The reduce() method applies a function against an accumulator and each value of the array (from left-to-right) to reduce it to a single value. https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

What is happening in the reduce here is storing the maximum value, it begins with 0, and on the first iteration compares with the value 4. As 4 is larger than 0 it is stored and becomes our new max. It then tests against 5 and as 5 is bigger than 4 it stores that as the new max, and so on.

Once it finishes going through it produces a maximum for that array and gives a Number as the result. So now the first iteration of the map which contained an array is changed to a Number, in this case the first item of the Array produced by Array.map should be 5.

The final output I suspect would be

[5, 27, 39, 1001]