Given the array
[
[Spain , Madrid , 10-12-2024]
[Spain , Barcelona , 10-15-2024]
[Suisse , Berne , 10-18-2024]
[France , Paris , 10-22-2024]
[France , Lyon , 10-24-2024]
]
How to easily get a new array ordered by countries
[
[Spain ,
[ Madrid , 10-12-2024],
[ Barcelona , 10-15-2024]
],
[Suisse ,
[ Berne , 10-18-2024]
],
[France ,
[ Paris , 10-22-2024],
[ Lyon , 10-24-2024]
]
]
When User clicks 1. the country, 2.the city, 3. defines a date he may do this in different ways, so the initial array may look like this
[
[Spain , Madrid , 10-12-2024]
[Suisse , Berne , 10-18-2024]
[France , Paris , 10-22-2024]
[France , Lyon , 10-24-2024]
[Spain , Barcelona , 10-15-2024] // ooops, I've forgotten this date...
]
3
Answers
Consider first sorting the data based on date and then utilizing
reduce
and the Nullish coalescing operator??=
:Focusing on what you could do differently, I too suggest to rather use an object-based structure:
Advantages:
Note: you can also use the Object.groupBy method on an array if you really want to stick with that structure.
For a similar result,
Object.groupBy
might be an approach: