Home > Software engineering >  Mutate an Array of Objects Using the Reduce Method and Spread Operator in JavaScript
Mutate an Array of Objects Using the Reduce Method and Spread Operator in JavaScript

Time:04-20

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": ""...}]

CodePudding user response:

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)

  • Related