arrays - How does the .reduce() function work with Math.max() in Javascript? - Stack Overflow

Can I get some help in understanding how the reduce function works in conjunction with Math.max() here?

Can I get some help in understanding how the reduce function works in conjunction with Math.max() here?

function rowHeights(rows){
    return rows.map(function(row){
        return row.reduce(function(max,cell){
            return Math.max(max, cell.minHeight());
        },0);
    });
}

The code if from the book
Eloquent Javascript

Can I get some help in understanding how the reduce function works in conjunction with Math.max() here?

function rowHeights(rows){
    return rows.map(function(row){
        return row.reduce(function(max,cell){
            return Math.max(max, cell.minHeight());
        },0);
    });
}

The code if from the book
Eloquent Javascript

Share Improve this question asked Feb 12, 2015 at 1:27 PositivelyDopedPositivelyDoped 291 silver badge3 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 4

I'll explain what this does line by line :)

 1    function rowHeights(rows) {
 2        
 3        return rows.map(function(row) {
 4            
 5            return row.reduce(function(max,cell) {
 6                return Math.max(max, cell.minHeight());
 7            },0);
 8            
 9        });
10    
11    }
  • Line 1: Declares function rowHeights, which takes an argument rows, a 2-dimensional array.

  • Line 3: Calls Array.prototype.map on the rows array, which essentially calls a function on each of the array elements within rows and replaces each element with the returned value of the function call

  • Line 5: On each of the sub-arrays (rows) within the array rows, call Array.prototype.reduce, which calls a function on each element to reduce the sub-array into a single element.

  • Line 5: Notice that there are 2 parameters for this function, max and cell. Think of these values as previous and current values for now

  • Line 6: Compare the previous (max parameter) value with the current (cell parameter) value using Math.max. Return the higher of the two.

  • Line 7: The second argument to Array.prototype.reduce is set to 0. This means that on the very first iteration, the initial value of max is 0.

Basically, what this does is loop through each row sub-array in the rows array. On each iteration, it pares the value returned from the previous iteration max with the current value. If the current value is larger than the previous, it returns a new max. max is initially set to 0. Once the reduce function has pleted, it replaces the row sub-array to the value of the highest number.

This function could be also written as:

function rowHeights(rows) {
    var newRowsArray = [];

    for (var i = 0, tmp = 0; i < rows.length; i++, tmp = 0) {
        for (var j = 0; j < rows[i].length; j++) {
            tmp = Math.max(tmp, rows[i][j]);
        }
        newRowsArray.push(tmp);
    }

    return newRowsArray;
}

Math.max returns the larger of its two parameters.

.reduce applies a transformation to every element in a collection (array) and returns a value.

In this case, the two parameters are the previous max and the current value of the cell. So, for a given row, iterate over the cells (.reduce) and return the largest value of cell.minHeight().


Array.prototype.map

Array.prototype.reduce

Math.max

I'm going to keep this explanation simple.

Math.max(1, 5) returns the largest number which would be 5 in this example.

Reduce basically goes through an array while passing on the previous result. For example:

[1,2,3,4,5].reduce(function (prevNum, currentNum) {
  return {{number to send to the next iteration as prevNum}};
});

So, if you put the two together, reduce will go through each number in the array and return the largest number found.

[1,2,3,4,5].reduce(function (prevNum, currentNum) {
  return Math.max(prevNum, currentNum);
});

Map will go through an array and create a new array with each index being the return value of the function passed.

[1,2,3,4,5].map(function (currentNum) {
  return currentNum + 1;
});
// this would return [2,3,4,5,6] because I added 1 to each number in the array

In the example from the book, the rowHeights function basically iterates over each row using map, and uses reduce to return the max height of a row of cells in a table. The result from this is basically an array of max heights that I'm assuming will be used to set the min-height of each row as the author states.

Imagine that you have a matrix with numbers [[31,10,23],[20,5,1],[12,31,41]]

rows.map(function (row) {}) will iterate over each item updating the array value with the returned value from the callback function.

Example: in the first iteration we have [31,10,23]

row.reduce(function (acumulated, current) {}) will be called three times with two arguments (previous returned value and current item from array) and will return the max between them.

   Math.max(0,31) = 31 
   Math.max(31,10) = 31 
   Math.max(31,23) = 31 // This is the returned value

the result will be the number 31. When it is returned to map function, it will be replace in the main array. So it will be something like:

   [31,[20,5,1],[12,31,41]]

and everything will repeat with [20,5,1] and [12,31,41]. All of them will have the max value at the end of all interation.

   [31,20,41]

It returns the maximum value of each row as an array. These are equivalent statements:

Math.max(1,2,36,9)
Math.max.apply(Math,[1,2,36,9])
[1,2,36,9].reduce(function(mx,c) { return Math.max(mx,c); } )

The first statement is really easy to understand. It returns the maximum value of those 4 numbers (ie 36). Now each of the following statements get progressively more intricate, but do the exact same thing as the first.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744091954a4557243.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信