Search code examples
javascriptarraysjavascript-objects

Creating a unique object on years and months based on array of dates


I am trying to create a unique object of years and months based on an array of dates, see what I mean below:

const availableDates = ["26-01-2022", "30-01-2022", "02-03-2022", "16-04-2022", "01-01-2023"]; // This list will be really long, just an example

I want to create a unique object like below using availableDates but having issues trying to figure it out:

const uniqueDates = {
  "2022": ["Jan", "Mar", "Apr"],
  "2023": ["Jan"]
};

If you have a better way that I achieve this, please let me know!

Thanks in advance


Solution

  • We can use Array.reduce to create the desired map, and using a Set to ensure we only keep a unique set of months for each year.

    const availableDates = ["26-01-2022", "30-01-2022", "02-03-2022", "16-04-2022", "01-01-2023", "01-01-2023"];
    
    const months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
    const uniqueDates = availableDates.reduce((acc, dt) => { 
        let [day, month, year] = dt.split("-");
        acc[year] = [...new Set(acc[year] || []).add(months[month - 1])];
        return acc;
    }, {})
    
    
    console.log("Unique object:", uniqueDates)