最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

sorting - Sort Javascript object by value alphabetically - Stack Overflow

programmeradmin1浏览0评论

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

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

Share Improve this question asked Feb 1, 2021 at 20:03 rob999rob999 633 bronze badges 1
  • 5 Although ES6 has specified the order of object properties, you generally shouldn't use objects if order is significant. Use an array. – Barmar Commented Feb 1, 2021 at 20:05
Add a ment  | 

2 Answers 2

Reset to default 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);

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

发布评论

评论列表(0)

  1. 暂无评论