Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the equivalent of .Max() in jquery

I was wondering how can we write a jquery statement to get the max value of a property of matched elements.

in LINQ we say something like this:

var maxHeight = list.Max(a=> a.Height);

what is the best way to do this in jquery?

as an example let's say we want to select the max numeric value of all :text elements inside a container:

var allInputs = $("#container :text");
// how to get the max of parseInt(item.val())?

of course having a loop over all elements is an option but I'm curious to know if there is a magic to do with jquery.

Regards.

like image 412
Mo Valipour Avatar asked Sep 05 '11 11:09

Mo Valipour


People also ask

Is there a max function in JavaScript?

max() The Math. max() function returns the largest of the numbers given as input parameters, or - Infinity if there are no parameters.

What is the max value in JavaScript?

Description. The MAX_VALUE property has a value of approximately 1.7976931348623157E+308 , or 21024 - 1. Values larger than MAX_VALUE are represented as Infinity and will lose their actual value.

What is '$' in jQuery?

$ is pretty commonly used as a selector function in JS. In jQuery the $ function does much more than select things though. You can pass it a selector to get a collection of matching elements from the DOM. You can pass it a function to run when the document is ready (similar to body.


2 Answers

One of the possible solutions is to use map function and then Math.max to the result:

var values = $.map($("input:text"), function(el, index) { return parseInt($(el).val()); });
var max = Math.max.apply(null, values);

If it is needed it might be written in one line.

fiddle: http://jsfiddle.net/WuVLr/1/

UPDATE:

Alternatively you can apply map in this way:

var values = $("input:text").map(function(index, el) { return parseInt($(el).val()); }).get();
like image 175
Igor Dymov Avatar answered Sep 27 '22 18:09

Igor Dymov


Based on all the conversation here and my search in the net we can say that (at this time) there is no robust built-in jquery way to calculate .max() and .min() of a property of elements matching a selector.

From what Igor suggested I came up with the following two jquery functions which you can add to your project if you need to use .max() and .min() functionalities over and over:

$.fn.max = function(selector) { 
    return Math.max.apply(null, this.map(function(index, el) { return selector.apply(el); }).get() ); 
}

$.fn.min = function(selector) { 
    return Math.min.apply(null, this.map(function(index, el) { return selector.apply(el); }).get() );
}

// Usage:

var maxWidth = $("a").max(function() {return $(this).width(); });
var minWidth = $("a").min(function() {return $(this).width(); });

See a demo here: http://jsfiddle.net/NF7v7/3/

like image 36
Mo Valipour Avatar answered Sep 27 '22 19:09

Mo Valipour