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

The problem is on the inner loop, when you try to find the max value for each array. On each iteration of the outer loop, you should reset long = arr[k][0]. It should not be reset to 0 since the max value may be smaller than 0. Note that this expects all subarrays to have at least one item.

As noted by @edc65, the declaration of long should occur at the start of the function to make it clear that long, as all local variables, has a function scope.


You only want one value per subarray. Therefore you should be adding one value for each iteration of the outer loop (main.push should be in the outer loop). The way it is currently, you are adding one value per subarray element.


In the if statement, your assignment is inverted. It should be

long = arr[k][i];

And the condition is also inverted. long stores the max value for each subarray. Therefore, you update it if you find a value greater than it:

if(arr[k][i]>long) {
    long = arr[k][i];
}

When pushing into the array use parenthesis, not brackets:

main.push(long);

Parenthesis are for calling methods. Brackets are for accessing properties in an object.

Final code

function largestOfFour(arr) {
    var main = [];
    var long;
    for(k=0;k<arr.length;k++){
       long = arr[k][0];
         for(i=0;i<arr[k].length;i++){
            if(arr[k][i]>long) {
                long = arr[k][i];
            }
        }
        main.push(long);
    }
    return main;
}

Math.max method

You can use Math.max to simplify your code

function largestOfFour(arr) {
    var main = [];
    for(k=0;k<arr.length;k++){
        var long = Math.max.apply(null, arr[k]);
        main.push(long);
    }
    return main;
}

As per @BillyMoon’s and @Tushar’s answers, this can be further simplified to an Array.map call.

Leave a Comment