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

101
Visualizações
Mutate an Array of Objects Using the Reduce Method and Spread Operator in JavaScript

I'm currently learning JavaScript and was trying to test the limitations of the Spread Operator along with the reduce() method.

Example:

const numArray = [1, 6, 9, 4, 21, 8, 15];

const sumEvenOdd = numArray.reduce((acc, current) => 
   current % 2 === 0 
      ? {...acc,'even': acc.even + current} 
      : {...acc,'odd': acc.odd + current}, 
      {"even": 0, "odd": 0}
);

console.log(sumEvenOdd); //{ even: 18, odd: 46 }  

As you could see from the above code, I was able to mutate the initial value of the reduce() method which is an object: {"even": 0, "odd": 0} to track the sum of the even and odd numbers of numArray and use the Spread Operator to fill-in the other remaining property.

Question:
Can I do the same thing if I have an array of objects as the initial value? e.g., [{"even": 0}, {"odd": 0}] and if not, what can I do as an alternative so I could fill-in the other properties that I didn't mention like for example if the objects also contain other properties? e.g., [{"even": 0, "color": ""...}, {"odd": 0, "color": ""...}]

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

0

yes, you can modify array with any props

you can use any type for reduce: objects, arrays, numbers, strings, boolean

A few examples with different types:

const concatNumbersAsString = [0,1,2].reduce((a,c) => a + c, '');

const flatNestedArrays = [[0],[1],[2]].reduce((a,c) => a.concat(c), [])

const checkBoolCondition = [0,1,2].reduce((a,c) => [1].includes(c), true)

const calculateSum = [0,1,2].reduce((a,c) => a + c, 0)

console.log('concatNumbersAsString', concatNumbersAsString)
console.log('flatNestedArrays', flatNestedArrays)
console.log('checkBoolCondition', checkBoolCondition)
console.log('calculateSum', calculateSum)

Modifying an array:

const numArray = [1, 6, 9, 4, 21, 8, 15];

const sumEvenOdd = numArray.reduce((acc, current) => 
   current % 2 === 0 
      ? acc.map(i => i.hasOwnProperty('even') ? {...i, even: i.even + current} : i)
      : acc.map(i => i.hasOwnProperty('odd') ? {...i, odd: i.odd + current} : i), 
      [{"even": 0, color: 'red'},{ "odd": 0, color: 'green'}]
);

console.log(sumEvenOdd)

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