I have an array of objects. From this array I want to create a sorted map by the key foo
. The values shall be arrays with the corresponding objects, sorted by the key bar
.
// input data
const arr = [{'foo': 42, 'bar': 7}, {'foo': 1, 'bar': 2}, {'foo': 1, 'bar': 1}];
// insert magic here
// This is the result (not sure how to correctly display a map)
{
1 -> [{'foo': 1, 'bar': 1}, {'foo': 1, 'bar': 2}],
42 -> [{'foo': 42, 'bar': 7}]
}
It's not too difficult to find a working solution. But I'm looking for a simple and fast solution, preferrably a one-liner. How can this be done?
My current endeavors
Currently I'm stuck with this line of code. It creates a map with arrays. Is there a way to at least include the sorting functionality for the keys in there? I could then do a second step and sort the arrays separately.
const result = new Map(arr.map(i => [i.foo, i]));