怎么样:
articleWithMaxNumber = articles.slice(0).sort(
function(x, y) { return y.number - x.number })[0]
如果你需要一个索引:
index = articles.indexOf(articleWithMaxNumber)
对于那些认为排序可能是获得最大值的过度杀伤力:
articleWithMaxNumber = articles.reduce(function(max, x) {
return x.number > max.number ? x : max;
})
下面是一个通用方法,如何使用 map-reduce 找到最大的函数应用程序:
function maxBy(array, fn) {
return array.map(function(x) {
return [x, fn(x)]
}).reduce(function(max, x) {
return x[1] > max[1] ? x : max;
})[0]
}
articleWithMaxNumber = maxBy(articles, function(x) { return x.number })
sort
与迭代方法相比,有些人担心该方法“慢”。这是一个使用这两种方法处理包含50000 个项目的数组的小提琴。该方法在我的机器上“慢”了大约50 毫秒。取决于应用程序,但在大多数情况下,这不值得谈论。sort
var articles = [];
var len = 50000;
while (len--) {
var article = {};
article.text = "foobar";
article.color = "red";
article.number = Math.random();
articles.push(article);
}
d = performance.now();
max1 = articles.slice(0).sort(
function(x, y) {
return y.number - x.number
})[0]
time1 = performance.now() - d
d = performance.now();
max2 = articles.reduce(function(max, x) {
return x.number > max.number ? x : max;
})
time2 = performance.now() - d
document.body.innerHTML = [time1, time2].join("<br>")