Marko
Marko

Reputation: 10992

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!

Upvotes: 1

Views: 313

Answers (4)

kennebec
kennebec

Reputation: 104760

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

Upvotes: 0

sled
sled

Reputation: 14625

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.

Upvotes: 0

Pointy
Pointy

Reputation: 413702

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.

Upvotes: 0

Justin Ethier
Justin Ethier

Reputation: 134167

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.

Upvotes: 3

Related Questions