I have an object:
[name: string]: Person;
I would like to sort it by key, which is Person's
name. Is it possible to do so or this kind of map is unsortable or I should replace it with collection of different type, which I would like to avoid.
I have an object:
[name: string]: Person;
I would like to sort it by key, which is Person's
name. Is it possible to do so or this kind of map is unsortable or I should replace it with collection of different type, which I would like to avoid.
An object is technically sortable, though doing so tends to raise the question of why you are using one in the first place.
However, to address your concern with as little hassle as possible, here's one way to affect the insertion order of an object's keys:
function sortMap(map, compare) {
return Object
.entries(map)
.sort(compare)
.reduce((map, [key, value]) => Object.assign(map, {
[key]: value
}), {})
}
console.log(sortMap({
"Joe": {},
"Bob": {},
"Alice": {},
"Kevin": {},
"Sarah": {}
}, ([a], [b]) => a.localeCompare(b)))
References:
As is stated in the linked answer, relying on the insertion order of an object does not guarantee the iteration order, since it is not in the specification, but it is currently a de-facto standard in many implementations, and it does not appear that this behavior will change in the future.
For a formal guarantee of iteration order by the specification, use a Map
, as recommended in comments.
As an addendum, here's how to sort a map's iteration order, if you should choose to use them instead:
function sortMap(map, compare) {
return new Map(
Array
.from(map)
.sort(compare)
)
}
let people = new Map([
['Joe', {}],
['Bob', {}],
['Alice', {}],
['Kevin', {}],
['Sarah', {}]
])
let sorted = sortMap(
people,
([a], [b]) => a.localeCompare(b)
)
console.log(Array.from(sorted))