What is the equivalent of .Max() in jquery
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();
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/
This could be a non-direct solution for that using an array:
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function() { var mySizes=new Array(); $("input[type=text]").each( function( intIndex ){ mySizes[intIndex] = $(this).val().length; }); var largest = mySizes.sort(function(a,b){return a - b}).slice(-1); alert("The maximun length is: " + largest); }); </script> </head><body> <input type="text" value="Test"id="1"/> <input type="text" value="Goodbye"id="2"/> <input type="text" value="Bye"id="3"/> <input type="text" value="Hello"id="4"/> <input type="text" value="Hello world!"id="5"/> <input type="text" value="Hi"id="6"/></body></html>
Regards