I have a map that’s declared like var cars = new Map<string, object>();, where the string is the model of the car and the object has information like year and price.
Therefore, the Map will look like this:
Map = [
'BMW' => {
id: 123,
price: 2000,
models: {...}
},
'Opel' => {
id: 1234,
price: 3500,
models: {...}
},
....
]
I would like to sort all the entires by the price field (asc, or desc).
I couldn’t figure out any solution, since iterating over the values would lose the keys, and solutions like I read around with ...cars.entries() doesn’t apply since the values are not iterable.
P.S. I am currently using TypeScript, but the solution for JS should apply nonetheless.
Edit: I tried converting the map to an array, like this:
const values = Array.from(this.cars.values());
values.sort((a, b) => {
return (a.price < b.price) ? -1 : 1;
});
But I had some troubles reconstructing the Map to keep the keys…