3

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() {
    ??
});
David542
  • 104,438
  • 178
  • 489
  • 842

6 Answers6

17

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);
Blazemonger
  • 90,923
  • 26
  • 142
  • 180
bfavaretto
  • 71,580
  • 16
  • 111
  • 150
8

You could do something like this:

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

var max = Math.max.apply(Math, ids);
Blender
  • 289,723
  • 53
  • 439
  • 496
  • Except this doesn't actually get the highest for me. The highest in the set I have is 20, whereas this gives me 9. – David542 Mar 12 '13 at 20:12
  • 2
    Other than being inefficient, this will not work as `.sort` in JS doesn't work with numbers as you'd expect. – Dogbert Mar 12 '13 at 20:14
  • @Dogbert: If you're going for efficiency, don't use jQuery in the first place. – Blender Mar 12 '13 at 20:26
2

Funny but this also works:

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

http://jsfiddle.net/N5zWe/

dfsq
  • 191,768
  • 25
  • 236
  • 258
  • Ideally sort comparator functions are supposed to return -1 ot 0 or 1. – Selvakumar Arumugam Mar 12 '13 at 20:21
  • @Vega I know, but in this case it's not necessary since we are looking for the max value. Anyway I provided this solution just for the sake of curiosity. Of course it sucks. – dfsq Mar 12 '13 at 20:22
2

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);
Blazemonger
  • 90,923
  • 26
  • 142
  • 180
  • [This is the fastest technique](http://jsperf.com/stack-overflow-question-15371102/2), if not necessarily the shortest code. – Blazemonger Mar 13 '13 at 14:45
0

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;
    }
});
jbabey
  • 45,965
  • 12
  • 71
  • 94
0
  var maxID = -1;
  $('.note-row').each(function() {
       var myid = parseInt($(this).attr('id'),10);
       if( maxID < myid ) maxID = myid;
  });
  // the value of maxID will be the max from id-s
Kovge
  • 2,019
  • 1
  • 14
  • 13