Ali Aslam
Ali Aslam

Reputation: 115

JavaScript finding the largest integer in an array of arrays

function largestOfFour(arr) {
    var newArray = [];
    for(var i =0; i <=arr.length-1; i++){
        console.log(arr[i]);
        newArray[i] = Math.max(arr[i]);
    }
    console.log(newArray);
              // You can do this!
    return newArray;
}

largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);

So I do not understand why I am getting NaN even though i have provided an argument within my math.max function. In the console.log within my for loop, i get each array within the main array to display. Meaning if I use the same arr[i] within the max function, it should give me the max of that sub Array.

Upvotes: 1

Views: 370

Answers (5)

Jerome Anthony
Jerome Anthony

Reputation: 8011

Using lodash

var x = ([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
_.flatten(x).max();

Upvotes: 0

Pastel Belem
Pastel Belem

Reputation: 46

Edited: In order to add values to the array, I'd suggest using the push methodn. As in: NewArray.push(Math.max(...sub[i])); or newarray.push(math.max.apply(null, sub[i]). An alternative is alocating, when declarating the array, the size it will take: Var newArray = new Array(arr.length); There's this new spread operator (...) in javascript !

Upvotes: -1

Daniel A. White
Daniel A. White

Reputation: 190907

If you want the ultimate max do this.

var original = [[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]];
Math.max.apply(null, original.map(function(arr) { return Math.max.apply(null, arr); }));

or if you want a the max of each array just do

original.map(function(arr) { return Math.max.apply(null, arr); });

Upvotes: 0

Oriol
Oriol

Reputation: 287970

You are passing an array to Math.max and expect it to return the maximum in that array.

However, Math.max returns the maximum among its arguments. So use

var newArray = [];
for(var i =0; i < arr.length; ++i)
  newArray[i] = Math.max.apply(void 0, arr[i]);

In ES6, you can use arrow functions and the spread operator to simplify:

arr.map(a => Math.max(...a));

Upvotes: 3

Kirill Slatin
Kirill Slatin

Reputation: 6143

It won't work like that. Math.max expect separate numbers. You can get desired output using apply

function largestOfFour(arr) {
    return arr.map(function(subArr){
        return Math.max.apply(Math, subArr);
    });
}

Upvotes: 2

Related Questions