Creating an array consisting of the largest values of each sub-array does not work as expected

前端 未结 4 1575
执念已碎
执念已碎 2020-12-01 18:49

Find the largest number in each of the sub-array and then make an array of those largest numbers.[[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1

4条回答
  •  旧巷少年郎
    2020-12-01 19:45

    I know the question here is to find a bug in the existing code, in case if you may want to optimise the code

    The original idea is of @thefourtheye. I'm just explaining this here.

    No need of nested loops, you can achieve this in single line.

    var arr = [[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]];
    
    var result = arr.map(Math.max.apply.bind(Math.max, null));
    
    document.write(result);
    console.log(result);

    How this works?

    The array.map function is iterating over each of the elements from array on which it is called. The function passed to the map here is apply with its this context bound to the Math.max and first argument bound to null.

    Math.max.apply.bind(Math.max, null) this basically calls the Math.max function on array as

    Math.max.apply(null, array);
    

    Update:

    With ES6, arrow function and spread operator, this can be made even smaller

    arr.map(e => Math.max(...e))
    

    var arr = [[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]];
    
    var result = arr.map(e => Math.max(...e));
    
    document.write(result);
    console.log(result);

提交回复
热议问题