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
…
A Map
object iterates and keeps its elements in insertion order. So only solution for you to create new Map
. Easiest way i think is to convert old map to array, sort it, and convert to a new map. Like this :
let newMap = new Map([...map].sort(([k, v], [k2, v2])=> {
if (v.price > v2.price) {
return 1;
}
if (v.price < v2.price) {
return -1;
}
return 0;
}));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With