-1

I have an object like this { alexa: 1, John: 5, Bill: 2 }

I need to sort by the value, from big to small, but I can not see how to do that. Any ideas?

2 Answers2

1

You can still get an array of the keys being sorted - then just loop the keys array to access your object in the correct order:

var obj = { alexa: 1, John: 5, Bill: 2 };
var sortedKeys = Object.keys(obj).sort(function(a, b) { 
    return obj[a] - obj[b] 
});

sortedKeys.forEach(function(k) {
    console.log(obj[k]);
});

Creating an array from the object:

var sortedArray = Object.keys(obj).sort(function(a, b) { 
    return obj[a] - obj[b] 
}).map(function(k) {
    var o = {};
    o[k] = obj[k];

    return o;
});
tymeJV
  • 103,943
  • 14
  • 161
  • 157
  • That works but the output that I need is {Alexa: 1, Bill : 2, John: 5} and when it is sorted, I need to know the key that belongs to each number, because the values can repeat... – user3474502 Jan 21 '16 at 21:08
  • Change the format into an array, something like `[ {name : 'Alexa', numb : 1}, {name : 'Bill', numb : 2} ]`, then you can sort it, and keep track – adeneo Jan 21 '16 at 21:09
  • @user3474502 Objects is *not* ordered. `{Alexa: 1, Bill : 2, John: 5}` is exactly the same as `{Alexa: 1, John: 5, Bill: 2 }` and sorting it is a nonsense question. – Derek 朕會功夫 Jan 21 '16 at 21:15
0

var objUnordered = { alexa: 1, John: 5, Bill: 2 };
var objOrdered = {};
var sortable = [];

for (var element in objUnordered){
  sortable.push([element, objUnordered[element]]);
}
sortable.sort(function(a, b) {return a[1] - b[1]})
for(var key in sortable){
  objOrdered[sortable[key][0]] = sortable[key][1];
}

console.log(objOrdered);  //print this ->  Object { alexa=1,  Bill=2,  John=5}
kpucha
  • 729
  • 5
  • 12