Mandatory one-liner solution:
Math.max.apply(null, $('option').map(function() { return $(this).html().length; }).toArray())
I'd say that Dogbert's solution is probably more readable, but there might still be some fun lessons in here. What's going on:
- using
.map
to get a result set of just the lengths
- using
.toArray
to make an actual array out of the result set, which would be required by .apply
- Passing the array to
Math.max
using apply
which will make the second argument the arguments
collection, i.e. equivalent of writing Math.max(5, 6, 12);
If you're using Roatin Marth's excellent array extensions, the code would look a bit neater:
Array.prototype.max = function() {
return Math.max.apply(null, this)
}
$('option').map(function() { return $(this).html().length; }).toArray().max();