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

74
Visualizações
Merge object data with same date

I have the following array I need help with.

let test = [
{
  date: ["2021-11-09", "2021-11-09", "2021-11-10", "2021-11-10"],
  amount: [0.5, 0.5, 1, 2],
}];

How can I merge the amounts that have the same date? I want the data to be returned as below:

date: ["2021-11-09", "2021-11-10"],
amount: [1, 3],

Thank you in advance!

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

As mentioned in the comments, this is just a 'group by' by date from the date array, summing the elements at the same index in the amount array.

let test = [
  {
    date: ['2021-11-09', '2021-11-09', '2021-11-10', '2021-11-10'],
    amount: [0.5, 0.5, 1, 2],
  },
];

const result = test.map(({ date, amount }) => {
  const grouped = date.reduce((a, d, i) => a.set(d, (a.get(d) ?? 0) + amount[i]), new Map());

  return {
    date: [...grouped.keys()],
    amount: [...grouped.values()],
  };
});

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

about 4 years ago · Juan Pablo Isaza Relatório

0

You could do with Array#map and Array#reduce. Then iterate the date array after that add the amount based in index of date array. Array#reduce return the object. So separate the date and amount use Object#values and Object#keys

let test = [ { date: ["2021-11-09", "2021-11-09", "2021-11-10", "2021-11-10"], amount: [0.5, 0.5, 1, 2], }];

const res = test.map(({date,amount})=> {
  const sumObj = date.reduce((acc,c,i)=>(acc[c] = (acc[c] || 0)+amount[i],acc),{})
  return ({date:Object.keys(sumObj),amount:Object.values(sumObj)})
})
  
console.log(res)

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