Reputation: 669
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 :
{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 }
Upvotes: 0
Views: 55
Reputation: 207511
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)
Upvotes: 1
Reputation: 35222
You can change the compareFunction to use 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
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 )
Upvotes: 1