Xavier
Xavier

Reputation: 8362

Compare Numbers in Javascript array to get largest number

I seem to have the right syntax but i keep getting a NaN value, i believe it has something to do with the propagation of the array, please could you check the code and see where i am going wrong.

var _array = new Array();

var _first = 1;
var _second = 4;

$('#con > div').each(function(index){

    var _data = $(this).css('left').split('px')[0];
    var _class = $(this).attr('class').split(' ')[0];

    _array[_first] = [_data];
    //_array[_second] = _class;

    _first++;
    _second++;

    if(index == 2){
        _first = 1;
        _second = 4;

        for(var i = 0; i < _array.length; i++)
        console.log(_array[i]);

        var large = Math.max.apply(Math, _array);
        console.log(large);

    }
});

Thanks

http://jsfiddle.net/LTMbr/1/

Upvotes: 0

Views: 650

Answers (2)

meouw
meouw

Reputation: 42140

The problem is that you are populating your array starting at index 1. If any of the arguments to Math.max cannot be converted to a number, NaN is returned
This is the case because _array[0] is undefined

Upvotes: 2

itsmatt
itsmatt

Reputation: 31406

So, I modified it a bit to see - http://jsfiddle.net/LTMbr/4/ and your _array[0] is undefined. So that's why your call to Math.max is returning NaN.

Upvotes: 2

Related Questions