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

前端 未结 4 1572
执念已碎
执念已碎 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:35

    Potentially simpler method to achieve same result - simplicity is prerequisite for reliability...

    function largestOfFour(arr){
        // assumes compatible browser, or shim: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/map#Browser_compatibility
        // map array each element into new value based on callback's return
        return arr.map(function(subarr){
            // sort to get highest value at front, and then return it
            return subarr.sort(function(a,b){
                return b-a;
            })[0];
        });
    }
    

    or with Math.max (see comments...)

    function largestOfFour(arr){
        // assumes compatible browser, or shim: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/map#Browser_compatibility
        // map array each element into new value based on callback's return
        return arr.map(function(subarr){
            // sort to get highest value at front, and then return it
            return Math.max.apply(null, subarr);
        });
    }
    

提交回复
热议问题