Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

111
Visualizações
How to find the same elements in two arrays and push them to form an object?

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
   }
 })
}) 
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

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; }

about 4 years ago · Juan Pablo Isaza Relatório

0

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];
  }
}

about 4 years ago · Juan Pablo Isaza Relatório

0

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; }

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda