0

Possible Duplicate:
How to sort an array of javascript objects?

I have output that looks like this:

[ { value: 1, count: 1 }, { value: 2, count: 2 } ]

I need to iterate through hashes in the array and then return the value number which has the highest count. Seems simple but I'm a bit stumped. I've tried using a separate array to save both sets of values but I can't figure out the best way to do it.

3
  • 1
    Do you actually need to sort the array to get the element with the highest count? Also, is this homework? Commented Jul 18, 2012 at 2:22
  • Nope, not homework. Also you're right, I guess sorting is not the right way to describe it. I simply need the value that corresponds to the highest count Commented Jul 18, 2012 at 2:22
  • 1
    Asked a bunch of times and JavaScript does not have hashes. ;) Commented Jul 18, 2012 at 2:24

1 Answer 1

2

You can do something like this:

var a = [{
    value: 1,
    count: 1
}, {
    value: 2,
    count: 2
}, {
    value: 7,
    count: 8
}, {
    value: 5,
    count: 0
}, {
    value: 10,
    count: 3
}];

// sorting using a custom sort function to sort the 
// greatest counts to the start of the array
// take a look here: http://www.w3schools.com/jsref/jsref_sort.asp
// to understand how the custom sort function works
// better references can be found 
// here: http://es5.github.com/#x15.4.4.11
// and here: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort
a.sort( function( v1, v2 ){
    return v2.count - v1.count;
});

for ( var i in a ) {
    console.log( a[i] );
}

// the greatest one is the first element of the array
var greatestCount = a[0];

console.log( "Greatest count: " + greatestCount.count );
Sign up to request clarification or add additional context in comments.

5 Comments

You da man, davidbuzatto
documentation: developer.mozilla.org/en/JavaScript/Reference/Global_Objects/… (most people prefer MDN or MSDN to w3schools)
Please don't reference w3schools. Much better to reference the relevant specification (ECMA5) and perhaps MDN or MSDN for examples.
jbabey and RobG, thanks for your tip! I will use better references now.
@davidbuzatto: Note the question is to return the value of the highest count. Hence, it should be: greatestCount.value

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.