I have a JS object as follows:
var obj = {"00:11:22:33:44:55" : "AddressB", "66:77:88:99:AA:BB" : "AddressA", "55:44:33:22:11:00" : "AddressC", "AA:BB:CC:DD:EE:FF" : "AddressD"};
The code as follows sorts it alphabetically via key:
sorted = Object.keys(obj)
.sort()
.reduce(function (accSort, keySort)
{
accSort[keySort] = obj[keySort];
return accSort;
}, {});
console.log(sorted);
Which produces the output:
{"00:11:22:33:44:55" : "AddressB", "55:44:33:22:11:00" : "AddressC", "66:77:88:99:AA:BB" : "AddressA", "AA:BB:CC:DD:EE:FF" : "AddressD"}
How can I sort the object alphabetically by value so the output is:
{"66:77:88:99:AA:BB" : "AddressA", "00:11:22:33:44:55" : "AddressB", "55:44:33:22:11:00" : "AddressC", "AA:BB:CC:DD:EE:FF" : "AddressD" }
You need to sort by the keys
by their values
first, then, use .reduce
to create the resulting ordered object:
const obj = {
"00:11:22:33:44:55": "AddressB",
"66:77:88:99:AA:BB": "AddressA",
"55:44:33:22:11:00": "AddressC",
"AA:BB:CC:DD:EE:FF": "AddressD"
};
const sorted = Object.keys(obj).sort((a,b) => obj[a].localeCompare(obj[b]))
.reduce((acc,key) => { acc[key] = obj[key]; return acc; }, {});
console.log(sorted);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With