Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

100
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!