0

If I have a javascript object like this:

{ 'apples':14, 'oranges': 1, 'bananas':4 }

How can I sort it to an Array, descending order, based on the value?

Result:

[ 'apples', 'bananas', 'oranges' ]

Because 14, 4, 1 ...descending order

3 Answers 3

4

Pull all the keys from the object into an array and sort the array.

var o = { 'apples':14, 'oranges': 1, 'bananas':4 };
var a = [];

for (var key in o) {
    a.push(key);
}
a.sort();

If you think you need to protect against properties that have been added to the Object prototype in an unfriendly way (or don't know), then you should do it like this:

var o = { 'apples':14, 'oranges': 1, 'bananas':4 };
var a = [];

for (var key in o) {
    if (o.hasOwnProperty(key)) {
        a.push(key);
    }
}
a.sort();

EDIT: now that the original question has been changed and the requirement is now that the keys are sorted in order by the value in the original object, that would have to be done differently:

var o = { 'apples':14, 'oranges': 1, 'bananas':4 };
var a = [];

for (var key in o) {
    if (o.hasOwnProperty(key)) {
        a.push(key);
    }
}
a.sort(function(x, y) {return(o.y - o.x);});
Sign up to request clarification or add additional context in comments.

9 Comments

Just an FYI: because of the way JavaScript objects are built, you should always wrap the inside of for-in loops with a hasOwnProperty: developer.mozilla.org/en/JavaScript/Reference/Global_Objects/…
If it's your own code and you know what's going on and nobody has extended the object class with additional properties in an unfriendly way for the for loop, there's no need to wrap it. If you don't know everything that's going on in the project, then I'd agree it is safer to protect from stray properties.
OK, I added the option for those who allow the object prototype to be messed with in their projects (something I don't allow).
@jfriend00, thanks, but this doesn't do what I wanted to do, I think it was a misundersrtanding
It generates the EXACT output you asked for. It puts all the keys into an array and sorts them in the order you show them in your example. GEEZ, now I see you've changed the requirements by editing your post. You want them sorted by the values, not by the keys.
|
1

Here is the ES5 way to do it:

var fruit = { 'apples':14, 'oranges':1, 'grapefruit':70, 'bananas':4 }

var orderedByDescendingQuantities = Object.keys(fruit).sort(function (x, y) {
    return fruit[y] - fruit[x];
});

alert(orderedByDescendingQuantities);

See http://jsfiddle.net/gh5x8/

Comments

1

here is my approach to this problem:

var o={ 'apples':14, 'oranges': 1, 'bananas':4 };
var a=[];
for(var fruit in o)
{
   if(o[fruit])
      a[fruit]=o[fruit];  i.e // a[apples]=14;
}

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

now a is sorted by the value.

console.log("Sorted Fruits:")
for(var fruit in o)
{
    if(o[fruit])
       console.log(fruit);
}

2 Comments

But 'a' is not [ 'apples', 'bananas', 'oranges' ], an array. 'a' is [ apples: 14, oranges: 1, bananas: 4 ]
This generates an array of values which isn't what they asked for. After some discussion, it appears that they want an array of keys sorted in the order of the values for those keys.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.