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

83
Visualizações
Count array with matching data then push to new array

I need to figure out how to count an array then combine only the matching ones.

example

const info = [ { name: 'John', date:'2022-04-11', type: '2', time: 5.00 },
               { name: 'Dave', date:'2022-04-12', type: '3', time: 6.00 },
               { name: 'John', date:'2022-04-11', type: '2', time: 2.00 },
               { name: 'John', date:'2022-04-15', type: '2', time: 3.00 } ];

The expected result should check for the same type, name and date them combine time. and the new array should look something like this.

It can be done with a forloop, but I would like to try creating a solution with es6.

But I am a bit unsure how to approach this.

const expected = [ { name: 'John', date:'2022-04-11', type: '2', time: 7.00 },
                     name: 'Dave', date:'2022-04-12', type: '3', time: 6.00 },
                     name: 'John', date:'2022-04-15', type: '2', time: 3.00 } ];
about 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

You could use a combination of .reduce and .find

const info = [ { name: 'John', date:'2022-04-11', type: '2', time: 5.00 },
               { name: 'Dave', date:'2022-04-12', type: '3', time: 6.00 },
               { name: 'John', date:'2022-04-11', type: '2', time: 2.00 },
               { name: 'John', date:'2022-04-15', type: '2', time: 3.00 } ];


const result = info.reduce((acc, x) => {
  const foundObj = acc.find(y => y.name === x.name && y.date === x.date && y.type === x.type);
  if (foundObj) {
    foundObj.time += x.time;
  } else {
    acc.push(x);
  }
  return acc;
}, []);
console.log(result)

about 4 years ago · Santiago Trujillo Relatório

0

You could for example create an object, where the key is a combination of name, date, type and the value is time

  let grouped = info.reduce((acc, curr) => {
  let key = `${curr.name}${curr.date}${curr.type}`;
  if (!acc[key]) {
    acc[key] = {
      name: curr.name,
      date: curr.date,
      type: curr.type,
      time: curr.time,
    };
  } else {
    acc[key].time += curr.time;
  }
  return acc;
}, {});

let expected = Object.values(grouped);
about 4 years ago · Santiago Trujillo 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