16

Consider the following HTML:

<div class="a" x="6"></div>
<div class="a" x="9"></div>
<div class="a" x="2"></div>
...
<div class="a" x="8"></div>

How would you find the maximal x value of all .a elements ?

Assume that all x values are positive integers.

Misha Moroshko
  • 166,356
  • 226
  • 505
  • 746

7 Answers7

26

Just loop over them:

var maximum = null;

$('.a').each(function() {
  var value = parseFloat($(this).attr('x'));
  maximum = (value > maximum) ? value : maximum;
});
Blender
  • 289,723
  • 53
  • 439
  • 496
10

I got another version:

var numbers = $(".a").map(function(){
    return parseFloat(this.getAttribute('x')) || -Infinity;
}).toArray();

$("#max").html(Math.max.apply(Math, numbers));

This uses the map function to extract the values of the x-Attributes, converts the object into an array and provides the array elements as function parameters to Math.max

The Math.max trick was stolen from http://ejohn.org/blog/fast-javascript-maxmin/

UPDATE

add "|| -Infinity" to process the case correctly, when no attribute is present. See fiddle of @kubedan

topek
  • 18,609
  • 3
  • 35
  • 43
1

Coming back to this with modern javascript:

let maxA = $(".a").get().reduce(function (result, item) {
  return Math.max(result, $(item).attr("x"));
}, 0);
Jay Irvine
  • 234
  • 4
  • 13
0

You could also use Array.sort in jQuery, as explained here then use $('.a:last') to get the selected element.

Community
  • 1
  • 1
Ben Taliadoros
  • 7,003
  • 15
  • 60
  • 97
0

I was doing some tests regarding this topic, and if performance matters, a old but gold simple for would be better than jQuery.map(), Math.apply() and also Array.sort():

var items = $(".a");
for (var i = 0; i < items.length; i++) {
  var val = items.eq(i).prop('x');
  if (val > max) max = val;
}

Here are the jsperf tests: http://jsperf.com/max-value-by-data-attribute. Nothing really drastic, but interesting anyway.

Erick Petrucelli
  • 14,386
  • 8
  • 64
  • 84
0
var max = null;

$('.a').each(function() {
  var x = +($(this).attr('x'));
  if (max === null || x > max)
    max = x;
}

alert(max === null ? "No matching elements found" : "The maximum is " + max);

Note the unary + operator to convert the attribute to a number. You may want to add some error checking to ensure it actually is a number - and that the attribute exists at all. You could change the selector to only select elements with the class and the attribute: $('.a[x]').

nnnnnn
  • 147,572
  • 30
  • 200
  • 241
0
var max =0;
$('.a').each(function(){

    if(parseFloat($(this).attr('x'))>max)
    {
         max = parseFloat($(this).attr('x')) ;
    }
});

alert(max);
Kanishka Panamaldeniya
  • 17,302
  • 31
  • 123
  • 193