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

299
Visualizações
How to get the sum of a key of consecutive array object and remove the duplicates?

I have a main array -

const arr = [
    {  description: 'Senior', amount: 50 },
    {  description: 'Senior', amount: 50 },
    {  description: 'Adult', amount: 75 },
    {  description: 'Adult', amount: 35 },
    {  description: 'Infant', amount: 25 },
    {  description: 'Senior', amount: 150 }
]

I want help with an es6 operation which will add the amount based on the key(description) and remove the duplicates.

Result array will somewhat look like -

const newArr = [
        {  description: 'Senior', amount: 100 },
        {  description: 'Adult', amount: 110 },
        {  description: 'Infant', amount: 25 },
        {  description: 'Senior', amount: 150 }
]

Please note, the grouping will be done only on consecutive objects with similar key.

I have been using the reduce operator to achieve this using the solution, but that removes the non-consecutive objects as well.

It would be really helpful if someone can help me with some es6 operators to perform the same operation.

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

0

this way

const arr = 
  [ { description: 'Senior', amount:  50 } 
  , { description: 'Senior', amount:  50 } 
  , { description: 'Adult',  amount:  75 } 
  , { description: 'Adult',  amount:  35 } 
  , { description: 'Infant', amount:  25 } 
  , { description: 'Senior', amount: 150 } 
  ] 

const newArr = 
  arr.reduce((res,{description,amount},i,{[i-1]:prev})=>
    {
    if (!prev || description != prev.description )
      res.push({description,amount})
    else
      res[res.length-1].amount += amount
    return res
    },[])

console.log( newArr )
.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