简体   繁体   English

按值对对象数组进行排序

[英]Sorting an array of objects by values

I need to sort an array of objects by its values and I use this code to do this:我需要按对象的值对对象数组进行排序,我使用以下代码来执行此操作:

function compare(a,b){return dict[a]-dict[b]} Object.keys(dict).sort(compare)

it works if each value is different, but if two objects have the same value, it leaves them in the order they appear in the array but I want them to be sorted alphabetically.如果每个值都不同,它会起作用,但是如果两个对象具有相同的值,它将按照它们在数组中出现的顺序保留它们,但我希望它们按字母顺序排序。 I couldn't figure out a way to do that.我想不出办法做到这一点。

dict = {a:1, d:4, c:2, b:4, e:5, f:3} should be: dict = {a:1, d:4, c:2, b:4, e:5, f:3}应该是:

{a:1, c:2, f:3, b:4, d:4, e:5 }

but I'm getting this:但我得到了这个:

{a:1, c:2, f:3, d:4, b:4, e:5 }

You can change the compareFunction to use localeCompare您可以更改 compareFunction 以使用localeCompare

dict[a] - dict[b] || a.localeCompare(b)

If dict[a] - dict[b] returns 0, it checks the next condition and sorts the keys alphabetically如果dict[a] - dict[b]返回 0,它将检查下一个条件并按字母顺序对键进行排序

Here's a snippet:这是一个片段:

 const dict = {a:1, d:4, c:2, b:4, e:5, f:3} function compare(a, b) { return dict[a] - dict[b] || a.localeCompare(b) } const sorted = Object.keys(dict).sort(compare).reduce((acc, k) => (acc[k] = dict[k], acc), {}) console.log( sorted )

So compare the keys if the diff is equal to zero因此,如果差异等于零,请比较键

 function compare(a, b) { var diff = dict[a] - dict[b] return diff === 0? a.localeCompare(b): diff } const dict = { a: 1, d: 4, c: 2, b: 4, e: 5, f: 3 } const result = Object.keys(dict).sort(compare).reduce((o, x) => ({...o, [x]: dict[x], }), {}) console.log(result)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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