Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the greatest Numerical Attribute [duplicate]

how do I select all the divs inside another div and find the greatest id attribute?

Consider the following code:

<div class="posts">
    <div class="post" data-id="5"></div>
    <div class="post" data-id="3"></div>
    <div class="post" data-id="1"></div>
    <div class="post" data-id="4"></div>
</div>    

What I want to do is, find the div that's having the greatest id attribute

I use the following code to grab the id attribute:

$('.posts .post').data('id');

But that returns the latest one, not the greatest.

like image 814
Akar Avatar asked Feb 11 '23 08:02

Akar


2 Answers

var max = 0;
$('.post').attr("data-id", function(i,v){
   max = +v > max ? +v : max;
});

console.log( max ); // 5

Another way:

var ids = $('.post').map(function(){
   return +this.dataset.id;            // or use jQ: return +$(this).data('id');
});

console.log( Math.max.apply(Math, ids) ); // 5

http://api.jquery.com/jquery.map/ used to return a new Array of the desired values.
How might I find the largest number contained in a JavaScript array? is used for the rest.

The unary + is used to convert any possible String number to Number.
To prevent a NaN resulting a mismatch caused by a mistakenly inserted Alpha character you can use:

return +this.dataset.id || 0; // Prevent NaN and turn "a" to 0
like image 160
Roko C. Buljan Avatar answered Feb 13 '23 22:02

Roko C. Buljan


If you like underscore, this can be done as follows with the max function.

var getIdAttr = function(el){ return el.getAttribute('data-id'); };
var elementIds = _.map($('.post'), getIdAttr);
var maxId = _.max(elementIds);

console.log(maxId); // 5
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.6.0/underscore-min.js"></script>
<div class="posts">
  <div class="post" data-id="3"></div>
  <div class="post" data-id="5"></div>
  <div class="post" data-id="1"></div>
  <div class="post" data-id="4"></div>
</div>
like image 45
Frank Bryce Avatar answered Feb 13 '23 20:02

Frank Bryce