Home > other >  How to find the same elements in two arrays and push them to form an object?
How to find the same elements in two arrays and push them to form an object?

Time:12-16

I have an array of objects with dates that are same or different:

const obj = [

 {'date': '2021-12-13T02:32:24.911 00:00'
  'id' : 'id1'
 },
 {'date': '2021-12-15T02:54:06.248 00:00'
  'id' : 'id2'
 },
 {'date': '2021-12-15T02:54:06.248 00:00'
  'id' : 'id3'
 },
 {'date': '2021-12-14T02:54:06.248 00:00'
  'id' : 'id4'
 },
 {'date': '2021-12-17T02:54:06.248 00:00'
  'id' : 'id5'
 },
 {'date': '2021-12-17T02:54:06.248 00:00'
  'id' : 'id6'
 },

]

I also have an array with dates of the current week starting from Saturday:

const weekDates = ['12/11/2021', '12/12/2021', '12/13/2021', '12/14/2021', '12/15/2021', '12/16/2021', '12/17/2021']

Ultimately, I'd like to find the same dates exist in both arrays and push the identified objects from the obj array to a new object.

const newObject = {
'Sat' : [],
'Sun' : [],
'Mon' : [{'date': '2021-12-13T02:32:24.911 00:00'
         'id' : 'id1'}],
'Tue' : [{'date': '2021-12-14T02:54:06.248 00:00'
           'id' : 'id4'}],
'Wed' : [{'date': '2021-12-15T02:54:06.248 00:00'
          'id' : 'id2'},
         {'date': '2021-12-15T02:54:06.248 00:00'
          'id' : 'id3'}],
'Thu' : [],
'Fri' : [ {'date': '2021-12-17T02:54:06.248 00:00'
           'id' : 'id5'},
          {'date': '2021-12-17T02:54:06.248 00:00'
           'id' : 'id6'},]
}

What I've tried:

newDates.forEach(weekday => {
 obj.map(obj => {
  const date = new Date(obj.date).toLocaleDateString()
   if(date.includes(weekday)) {
    // some code here
   }
 })
}) 

CodePudding user response:

You can do it by using forEach helper from Array and also toLocaleDateString helper from Date, like this:

const obj = [
 {'date': '2021-12-13T02:32:24.911 00:00',
  'id' : 'id1'
 },
 {'date': '2021-12-15T02:54:06.248 00:00',
  'id' : 'id2'
 },
 {'date': '2021-12-15T02:54:06.248 00:00',
  'id' : 'id3'
 },
 {'date': '2021-12-14T02:54:06.248 00:00',
  'id' : 'id4'
 },
 {'date': '2021-12-17T02:54:06.248 00:00',
  'id' : 'id5'
 },
 {'date': '2021-12-17T02:54:06.248 00:00',
  'id' : 'id6'
 },
];
const weekDates = ['12/11/2021', '12/12/2021', '12/13/2021', '12/14/2021', '12/15/2021', '12/16/2021', '12/17/2021'];

const days =["Sun","Mon","Tue","Wed","Thu","Fri","Sat"]
const newObject= {Sat:[], Sun: [], Mon: [], Tue:[], Wed:[], Thu:[], Fri: []};

obj.forEach(item => {
    const dateObj = new Date(item.date)
    if( weekDates.includes( dateObj.toLocaleDateString() ) ){
        const day = days[dateObj.getDay()]
        newObject[day].push(item)
    }
})

console.log(newObject);
.as-console-wrapper { max-height: 100% !important; top: 0; }

CodePudding user response:

For your specific problem, we can use Date.prototype.toDateString() to get the day of the week and play with it.

const firstArray = [{'date': '2021-12-13T02:32:24.911 00:00','id' : 'id1'}];
const secondArray = ['12/11/2021'];

const datesExistsInBothArrays = firstArray.filter(({ date, id } => {
  const firstArrayDate = new Date(date).valueOf();
  for (const secondDate of secondArray) {
    const secondArrayDate = new Date(secondDate).valueOf();
    if (firstArrayDate === secondArrayDate) return true;
  }
  return false;
});

const result = {};
for (const date of datesExistsInBothArrays) {
  const day = date.toDateString().split(' ')[0];
  if (result[day]) {
    result[day].push(date);
  } else {
    result[day] = [date];
  }
}

CodePudding user response:

You could use some helpers, one array for the days, one object as reference to the days by taking a part if ISO string and collect all data to their days.

const
    weekDates = ['12/11/2021', '12/12/2021', '12/13/2021', '12/14/2021', '12/15/2021', '12/16/2021', '12/17/2021'],
    days = ['Sat', 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri'],
    objects = [{ date: '2021-12-13T02:32:24.911 00:00', id: 'id1' }, { date: '2021-12-15T02:54:06.248 00:00', id: 'id2' }, { date: '2021-12-15T02:54:06.248 00:00', id: 'id3' }, { date: '2021-12-14T02:54:06.248 00:00', id: 'id4' }, { date: '2021-12-17T02:54:06.248 00:00', id: 'id5' }, { date: '2021-12-17T02:54:06.248 00:00', id: 'id6' }],
    getISODate = s => s.replace(/^(..)\/(..)\/(....)$/, '$3-$1-$2'),
    reference = Object.fromEntries(
        weekDates.map((date, i) => [getISODate(date), days[i]])
    ),
    result = objects.reduce(
        (r, o) => (r[reference[o.date.slice(0, 10)]].push(o), r),
        Object.fromEntries(days.map(d => [d, []]))
    );

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

  • Related