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.

Community
  • 1
  • 1
dsp_099
  • 5,801
  • 17
  • 72
  • 128
  • 1
    Do you actually need to sort the array to get the element with the highest `count`? Also, is this homework? – Waleed Khan Jul 18 '12 at 02: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 – dsp_099 Jul 18 '12 at 02:22
  • 1
    Asked a bunch of times and JavaScript does not have hashes. ;) – epascarello Jul 18 '12 at 02:24

1 Answers1

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 );
davidbuzatto
  • 9,207
  • 1
  • 43
  • 50
  • You da man, davidbuzatto – dsp_099 Jul 18 '12 at 02:35
  • documentation: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort (most people prefer MDN or MSDN to w3schools) – jbabey Jul 18 '12 at 02:38
  • Please don't reference w3schools. Much better to reference the relevant specification ([ECMA5](http://es5.github.com/#x15.4.4.11)) and perhaps [MDN](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort) or MSDN for examples. – RobG Jul 18 '12 at 02:38
  • jbabey and RobG, thanks for your tip! I will use better references now. – davidbuzatto Jul 18 '12 at 02:41
  • @davidbuzatto: Note the question is to return the value of the highest count. Hence, it should be: greatestCount.value – Abhishek Mehta Jul 18 '12 at 04:20