Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get highest id using javascript

I have a bunch of note divs in the following format:

<div class="note-row" id="1">
<div class="note-row" id="2">
<div class="note-row" id="4">
<div class="note-row" id="5">
<div class="note-row" id="6">

How would I get the largest id using javascript? So far I have:

$('.note-row').each(function() {
    ??
});
like image 850
David542 Avatar asked Oct 28 '25 06:10

David542


1 Answers

Quick and dirty way:

var max = 0;
$('.note-row').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){
    return Math.max(a, b.id)
}, Number.NEGATIVE_INFINITY);
like image 113
bfavaretto Avatar answered Oct 30 '25 22:10

bfavaretto