James George Dunn James George Dunn - 2 months ago 11
Javascript Question

Trying to get the tallest element but returning NaN

I'm trying to get the tallest height of some elements using the following.

var blocks = [];

for(var i = 1; i < 100; i++) {
blocks[i] = $('.blocks .block-' + i).outerHeight();
}

var tallest = Math.max.apply(Math, blocks);

console.log(tallest);


The heights are getting stored fine within the blocks array but when I output the tallest variable it's just coming up with NaN.

Answer

In your code, for loop start with 1 instead of 0 so first element of array got undefined and tallest return NaN.

Instead of adding value to individual array element using blocks[i]. Use push for array.

var blocks = [];

for(var i = 1; i < 100; i++) {
    blocks.push($('.blocks .block-' + i).outerHeight() || 0);
}

var tallest = Math.max.apply(Math, blocks);

console.log(tallest);

Check snippet

var blocks = [];

for (var i = 1; i < 10; i++) {
  blocks[i] = i;
}
var tallest = Math.max.apply(Math, blocks);
snippet.log('Using element : ' + blocks);
snippet.log('Using element tallest is : ' + tallest);

blocks = [];

for(var j = 1; j < 10; j++) {
    blocks.push(j);
}

tallest = Math.max.apply(Math, blocks);

snippet.log('Using push tallest element : ' + tallest);
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>