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