简体   繁体   中英

Sort Javascript object by value alphabetically

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM