I want to sort my Javascript object descending, but all solutions I see makes them into arrays (which I don't want). Here is my object:
var obj = {
"and":2,
"two":1,
"too":1,
"mother":3
}
I want this object to look like this instead:
var obj = {
"mother":3
"and":2,
"two":1,
"too":1
}
The property's name sorting doesn't matter, so I don't care about it being two,too
. All I care about is the property's value being sorted. An ES6 friendly one-liner would be great, but it's definitely not required.
Thanks.
EDIT: I finally got something working, although it's really, really bad.. really bad.
function sortObject(obj) {
var sortable=[];
var newObject = {};
for(var key in obj)
if(obj.hasOwnProperty(key))
sortable.push([key, obj[key]]); // each item is an array in format [key, value]
sortable.sort(function(a, b) {
return b[1]-a[1];
});
for(i = 0; i < sortable.length; i++) {
newObject[sortable[i][0]] = sortable[i][1];
}
return newObject;
}
I mean yeah it works, that's all that matters.