Currently delving into the world of JavaScript and decided to put the Spread Operator and reduce() method to the test.
Here's an 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 }
Looking at the code above, it's fascinating how I managed to adjust the original value of the reduce() method (an object: {"even": 0, "odd": 0}) to keep track of the total of even and odd numbers in the numArray, utilizing the Spread Operator to complete the remaining property.
Question:
If I had an array of objects as the initial value, like [{"even": 0}, {"odd": 0}], can I achieve the same outcome? If not, what alternative approach should I take to fill in the other properties, especially if the objects have additional attributes? For instance, [{"even": 0, "color": ""...}, {"odd": 0, "color": ""...}]