简体   繁体   中英

How do I sort this javascript object?

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

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

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

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM