I have a list of different events called events
. This contains the date of an event. I want to get all the unique years and months. This should be sorted in ascending order.
What I would like to have:
unique = {
"2023":[
"January", "October"],
"2024":[
"March"]
}
My input array:
events = [
{
"eventid": 6,
"name": "Event 1",
"description": "This is the first event.",
"date": "10.10.2023",
"status": "XO"
},
{
"eventid": 8,
"name": "Event 2",
"description": "This is another event",
"date": "14.01.2023",
"status": "XO"
},
{
"eventid": 8,
"name": "Event 3",
"description": "This is the last event",
"date": "14.03.2024",
"status": "OS"
}
]
CodePudding user response:
Loop over array, parse date and fill result object, then loop over existing keys, sort values in array and map month number to name. You can map them manually or use US or any other locale to get the month names.
const result = {};
for (let e of events) {
const [_, m, y] = e.date.split(".")
const yn = parseInt(y);
const mn = parseInt(m);
if (!result[yn]) result[yn] = [];
if (!result[yn].includes(mn)) result[yn].push(mn)
}
for (let y in result) {
result[y] = result[y].sort().map(m => new Date(2020, m - 1, 1).toLocaleString("en-US", {
month: "long"
}));
}
console.log(result);
<script>
const events = [{
"eventid": 6,
"name": "Event 1",
"description": "This is the first event.",
"date": "10.10.2023",
"status": "XO"
},
{
"eventid": 8,
"name": "Event 2",
"description": "This is another event",
"date": "14.01.2023",
"status": "XO"
},
{
"eventid": 8,
"name": "Event 3",
"description": "This is the last event",
"date": "14.03.2024",
"status": "OS"
}
]
</script>