Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the highest and lowest values of a certain attribute in jQuery or Javascript

I have the following divs:

<div id="2" class="maindiv">test</div>
<div id="5" class="maindiv">test</div>
<div id="3" class="maindiv">test</div>
<div id="1" class="maindiv">test</div> 
<div class="maindiv">test</div>     
<div id="4" class="maindiv">test</div>    

How to get the highest id (5) and the lowest id (1) in jQuery or Javascript?

like image 418
Michael Samuel Avatar asked Feb 08 '13 15:02

Michael Samuel


4 Answers

To achieve this you can create an array containing all the id values, then use Math to get the highest/lowest:

var ids = $('.maindiv[id]').map((i, el) => parseInt(el.id, 10)).get();
var lowest = Math.min.apply(Math, ids); // = 1
var highest = Math.max.apply(Math, ids); // = 5

console.log(`${lowest} => ${highest}`);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="2" class="maindiv">test</div>
<div id="5" class="maindiv">test</div>
<div id="3" class="maindiv">test</div>
<div id="1" class="maindiv">test</div>
<div class="maindiv">test</div>
<div id="4" class="maindiv">test</div>

Note the [id] attribute selector is required, otherwise 0 is assumed for the missing value.

If you need IE support, you need to use an anonymous function instead of the arrow function:

var ids = $(".maindiv[id]").map(function() {
  return parseInt(this.id, 10);
}).get();
like image 185
Rory McCrossan Avatar answered Sep 20 '22 04:09

Rory McCrossan


function minMaxId(selector) {
  var min=null, max=null;
  $(selector).each(function() {
    var id = parseInt(this.id, 10);
    if ((min===null) || (id < min)) { min = id; }
    if ((max===null) || (id > max)) { max = id; }
  });
  return {min:min, max:max};
}

minMaxId('div'); // => {min:1, max:5}

http://jsfiddle.net/qQvVQ/

like image 23
maerics Avatar answered Sep 18 '22 04:09

maerics


var min = Number.MAX_VALUE, max = Number.MIN_VALUE;
$(".maindiv").each(function () {
    var id = parseInt(this.id, 10);
    if (id > max) {
        max = id;
    }
    if (id < min) {
        min = id;
    }
});
like image 28
Explosion Pills Avatar answered Sep 21 '22 04:09

Explosion Pills


Create a global variable and compare it to each element using Math.max inside a loop.

var maxval = Number.MIN_VALUE,
    minval = Number.MAX_VALUE;

$('div').each(function () {
    var num = parseInt(this.id, 10) || 0; // always use a radix
    maxval = Math.max(num, maxval);
    minval = Math.min(num, minval);
});

console.log('max=' + maxval);
console.log('min=' + minval);

http://jsfiddle.net/mblase75/gCADe/

like image 25
Blazemonger Avatar answered Sep 20 '22 04:09

Blazemonger