0

I have 3 different arrays which contain an object with public holiday data (based on the region in the world e.g Mexico, Canada, US). I want to organise the data (store a combination of it all in its own array) so that if a regions share the same public holiday for example name: 'Christmas Day' date: 2021-12-25 then it only stores this once rather than for each region which is what its doing at the moment. The main issue is theres a problem with a lot of duplicate data inside allPublicHolidays function & i'm getting lost when it comes to the checkIfSame forEach loop as there is probably a much nicer way to do this.

The array data looks like this per region:

[
  {
    date: '2021-05-31 00:00:00',
    name: 'Spring bank holiday',
  },
  {
    date: '2021-12-25 00:00:00',
    name: 'Christmas Day',
  },
  {
    date: '2021-12-26 00:00:00',
    name: 'Boxing Day',
  }
]

The idea I had is to use a forEach loop for each region which pushes the data from each to its own array but checks the array each time it processes a holiday to make sure it doesn't already exist within the array. Before pushing it calls a function to check if the name data is the same as the array.

Here is what I have so far:


const regionUS = usArrayData;
const regionMX = mxArrayData;
const regionCA = caArrayData;
let allPublicHolidays = [];

function checkIfSame(name1, array) {

 let boolean = false;

  if (array) {
    array.forEach((arr) => {
      if (name1 == arr.name) {
         boolean = true;
        }
      })
     }
    return boolean;
}

regionUS.forEach((USholiday) => {

if (!checkIfSame(USholiday.name, allPublicHolidays)) {
 allPublicHolidays.push(USholiday);
}

});

regionMX.forEach((MXholiday) => {

if (!checkIfSame(MXholiday.name, allPublicHolidays)) {
 allPublicHolidays.push(MXholiday);
}

});

Any help with storing all data in one array minus duplicates based on object.name && object.date would be really appreciated.

Thank you
ste
  • 135
  • 1
  • 6
  • 20
  • 1
    `var o={}; arr1.concat(arr2).concat(arr3).filter(x=>o[x.date] ? "" : (o[x.date]=1))` – dandavis Aug 04 '21 at 20:37
  • After merging arrays with concat, you can look [here](https://stackoverflow.com/questions/2218999/how-to-remove-all-duplicates-from-an-array-of-objects), maybe you find answer – Nikola Pavicevic Aug 04 '21 at 20:56

0 Answers0