Say I have an object like:
{A:5, B:3, C:-7, D:0}
I want to get an Array of its keys in asec/desc order like:
['C','D','B','A']
What is the best way to achieve this?
You can simply sort the keys, with Array.prototype.sort with the difference between the values of the corresponding keys, like this
console.log(Object.keys(data).sort(function(a, b) {
return data[a] - data[b];
}));
# [ 'C', 'D', 'B', 'A' ]
To sort in the reverse order, simply find the difference between the values of b and a, like this
console.log(Object.keys(data).sort(function(a, b) {
return data[b] - data[a];
}));
# [ 'A', 'B', 'D', 'C' ]