簡體   English   中英

如何以最優雅的方式從javascript中的對象數組中獲取最大值?

[英]How to get the largest value from array of objects in javascript, in the most elegant way?

[Object { curr="SEK", antal=7}, Object { curr="JPY", antal=1}, Object { curr="DKK", antal=1}]

我可以創建一個新數組並對其進行排序。 但是我想按antal屬性對對象數組進行排序。 如何在純JavaScript中做到這一點。

不需要jQuery解決方案!

您可以使用自定義函數進行排序。

例如:

myArray.sort(function(a, b){
  return a.antal - b.antal;
})

有關更多信息,請參閱教程排序對象數組

function largestAntal(arr) {
  var rv = null, max = null;
  for (var i = 0; i < arr.length; ++i)
    if (max === null || arr[i].antal > max) {
      max = arr[i].antal;
      rv = arr[i];
    }
  }
  return rv;
}

如果您想要的只是具有最大“antal”值的對象,這將比排序更快。

您可以使用Array.sort

var a = [{ curr: "SEK", antal: 7}, { curr: "JPY", antal: 1},  { curr: "DKK", antal: 1}];

a.sort(function(left, right) { return left.antal < right.antal ? 1 : 0; }) 

這會給你:

[Object { curr="SEK", antal=7}, Object { curr="JPY", antal=1}, Object { curr="DKK", antal=1}]

如果您想反過來,只需在sort(..)函數中進行比較即可。

reduce將通過數組一次返回單個值。

var a = [{curr:“ XEK”,antal:2},{curr:“ SEK”,antal:7},{curr:“ JPY”,antal:1},{curr:“ DKK”,antal:1 }];

var min= a.reduce(function(a, b){
    return a.antal> b.antal? a:b;
});

* 警告('curr ='+ min.curr +',antal ='+ min.antal); 返回值>> curr = SEK,antal = 7 *

對於舊版瀏覽器,您可以減少 -

if(![].reduce){
    Array.prototype.reduce= function(fun, temp, scope){
        var T= this, i= 0, len= T.length, temp;
        if(typeof fun=== 'function'){
            if(temp== undefined) temp= T[i++];
            while(i < len){
                if(i in T) temp= fun.call(scope, temp, T[i], i, T);
                i++;
            }
        }
        return temp;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM