-4

I have an array of objects, and i am basically breaking my head on sorting it,my array is something like dis :

var myArray = [{1:3},{3:19},{5:53},{6:26},{e:53},{c:107},{B: 2},{f: 5}];

But i have to sort this in such a way that my final output is something like this:

 myArray = [{c:107},{5:53},{e:53},{6:26},{3:19},{f: 5},{1:3},{B: 2}];

i.e.; based on the value in each object of array element, the array should sorted in descending order.

Thank you in advance.

user3365783
  • 107
  • 1
  • 9
  • 1
    Array sorting is relatively simple. Use the .sort method, obtain the property you want to compare by from the two arguments, then compare them and return -1, 0, or 1. If you are having problems with one of those steps, ask a question on that step, not the whole process. – Kevin B Jun 13 '14 at 14:28
  • Just write a comperator function and use [`sort()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort). – Sirko Jun 13 '14 at 14:28
  • why am i getting all the negative votes :(, i din know that array sort took a function reference and moreover i am a complete new bie :( – user3365783 Jun 13 '14 at 14:35
  • @user3365783 Provide the research you did and attempts at solving the problem, otherwise it seems like you're expecting someone to just write code for you (that's not what this site is about). MDN has good documentation on JavaScript overall, and it could've easily been found there: https://developer.mozilla.org/en-US/docs/Web/JavaScript – Ian Jun 13 '14 at 14:44
  • yes i will provide research on attempts also from now on..thank you for the link:)..really needed it..i understand your point. – user3365783 Jun 13 '14 at 14:57

1 Answers1

2

You can simply use a comparator function in Array.prototype.sort like this

console.log(myArray.sort(function(first, second) {
    return second[Object.keys(second)[0]] - first[Object.keys(first)[0]];
}));

Since the key will be different in every object, we get the actual list of keys and taking only the first item in it.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497