Skip to content Skip to sidebar Skip to footer

Get Highest Id Using Javascript

I have a bunch of note divs in the following format:
).each(function() { max = Math.max(this.id, max); }); console.log(max);

This is a little shorter and more sophisticated (for using reduce, and also allowing negative ids down to Number.NEGATIVE_INFINITY, as suggested by Blazemonger):

var max = $('.note-row').get().reduce(function(a, b){
    returnMath.max(a, b.id)
}, Number.NEGATIVE_INFINITY);

Solution 2:

You could do something like this:

var ids = $('.note-row').map(function() {
    returnparseInt(this.id, 10);
}).get();

var max = Math.max.apply(Math, ids);

Solution 3:

Funny but this also works:

var max = $('.note-row').sort(function(a, b) { return +a.id < +b.id })[0].id;

http://jsfiddle.net/N5zWe/

Solution 4:

In the interest of completeness, an optimized Vanilla JS solution:

var n = document.getElementsByClassName('note-row'),
    m = Number.NEGATIVE_INFINITY,
    i = 0,
    j = n.length;
for (;i<j;i++) {
    m = Math.max(n[i].id,m);
}
console.log(m);

Solution 5:

The same way you'd find any max, loop:

var max = -999; // some really low sentinel

$('.note-row').each(function() {
    var idAsNumber = parseInt(this.id, 10);
    if (idAsNumber  > max) {
        max = idAsNumber;
    }
});

Post a Comment for "Get Highest Id Using Javascript"