简体   繁体   中英

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}]

I could create a new array and sort it. But I want to sort the array of objects by the antal property. How to do that in pure javascript.

No jquery solutions wanted!

You can use a custom function to do the sort.

For example:

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

For more information see the tutorial Sorting an array of objects .

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;
}

That'll be faster than sorting if all you want is the object with the biggest "antal" value.

You can use 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; }) 

this will give you:

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

if you want it the other way around, just play with the comparison inside the sort(..) function.

reduce will return a single value with one pass through the array.

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;
});

* alert('curr='+min.curr+', antal='+min.antal); returned value>> curr= SEK, antal= 7 *

for older browsers you can shim reduce-

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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM