ECMAScript 5th Edition introduces a few higher-order functions for arrays -- yay!.
One is Array.reduce
(also known as left fold):
Thus, this can be solved as:
var arr = [-42, 0, 8]
var res = arr.reduce(function (prev,cur) {
return cur > prev ? cur : prev
}, -Infinity)
res // 8
Not nearly as "elegant" in this case as applying the array as the parameters to Math.max
, but higher-order functions can make good additions to a "toolbox" ;-) Consider the slight modification to find the longest string in an array:
var arr = ["Hello", "World!!!", "Wut?"]
var res = arr.reduce(function (prev,cur) {
return cur.length > prev.length ? cur : prev
}, "")
res // "World!!!"
Try that with Math.max
or Array.sort
and index/pop ;-)
Happy coding.
While the above is for 5th Edition, a trivial reduce function can be written for ECMAScript 3rd Edition (aka JavaScript 1.5) and equivalent functionality is part of a number of libraries:
function reduce (arr, fn, v) {
for (var i = 0; i < arr.length; i++) {
v = fn(v, arr[i])
}
return v
}
// used as:
reduce(arr, function (prev,cur) { ... }, initValue)
(This could be added to the Array prototype, but I consider mucking with core prototypes fairly ugly.)