5

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" }

1
  • 5
    Although ES6 has specified the order of object properties, you generally shouldn't use objects if order is significant. Use an array. Commented Feb 1, 2021 at 20:05

2 Answers 2

9

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

Sign up to request clarification or add additional context in comments.

Comments

3

Use Object.entries() to get a 2-dimensional array of keys and values. Sort that by the values, then create the new object with reduce().

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"}; sorted = Object.entries(obj) .sort(([key1, val1], [key2, val2]) => val1.localeCompare(val2)) .reduce(function(accSort, [key, val]) { accSort[key] = val; return accSort; }, {}); console.log(sorted);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.