![](/img/trans.png)
[英]Using map with reduce in javascript to filter objects in an array
[英]Using javascript reduce to filter an array of objects, to find the lowest calculated stats
所以,我寫了這個for循環
if (specimins.length > 0) {
var max = specimins[0]
for (var x = 1; x < specimins.length; x++) {
if ((max.weight+max.height) > (specimins[x].weight+specimins[x].height)) {
max = specimins[x]
}
}
specimins = [max]
}
但是,這是相當麻煩的。 因此,基本上,要遍歷一系列樣本才能找到計算出的最低總重量+身高。 有什么好方法可以使用array.reduce()嗎? 我已經嘗試了一些嘗試,但是大多數嘗試對我都無效。
任何幫助表示贊賞。 謝謝!
您可以使用reduce
來獲得具有最低高度和寬度的元素,如下所示:
var max = specimens.reduce(function(a, b) {
return (a.width + a.height) < (b.width + b.height) ? a : b
}, specimens[0])
但是,在這種情況下,使用標准的for循環並沒有錯。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.