Changing Objects in an Array by Leveraging the Reduce Method with the Spread Operator in JavaScript

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

Answer №1

Yes, it is possible to customize an array with any properties

Various data types can be used in reduce:

objects, arrays, numbers, strings, boolean

Here are a few examples showcasing 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)

Customizing 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)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Resetting forms in AngularJS 1.5.6 with ng-messages functionality

I have been searching for solutions on Stackoverflow regarding how to reset a form, but I am still not able to figure it out. Even though the input was valid, the error message kept showing up. Upon debugging the application, I noticed that the message was ...

Popup Triggered by a JavaScript Timer

Seeking assistance in creating a straightforward timer-based popup. Once the timer hits 10 seconds, the popup should become visible. The timer should pause or stop, and after clicking the 'ok' button on the popup, the timer should reset to 0. Can ...

Leverage the package.json script without relying on any yarn/npm commands

Can scripts commands be executed within the package.json file without needing to include yarn or npm? For example: "scripts": { "get": "node index.js" } Currently, in order to run this script I have to use yarn get [ar ...

Invisible enigmatic anomaly detected on non-existent line within the realm of Node.js

Today, when I tried to run my app on node, it encountered an unexpected token error at line 219 in the file. The full error log is as follows: syberic@syberic:~/Web/lotalot$ node app.js /home/syberic/Web/lotalot/config/passport.js:219 }); ^ SyntaxError: ...

What is the method for generating a fresh array that includes information from a different array using React Native?

Can you guide me on how to generate a new array from an existing one? The array I have is called data1. this.state = { data1: [ {'x':'%20', 'y':11, 'z':'sunday'}, {'x':' ...

Suggestions for this screenplay

I am completely new to the world of coding and computer languages, and I could use some guidance on how to utilize this script for a flash sale. setInterval(function() { var m = Math.floor((new Date).getTime()/1000); if(m == '1476693000000& ...

Combining Multidimensional Array with Matching Key Using PHP

I've been grappling with this specific problem over the past few days. While I have searched through StackOverflow, I have only found solutions that assume all keys in the multidimensional array are identical. My challenge involves merging a multidim ...

The JavaScript file specified in the script tag's src attribute was successfully downloaded, but it did not execute as expected after being fetched

I've implemented an ajax call using jQuery in the following manner: $.ajax({ type: 'GET', url: 'edit.htm', success: function(data){ container.html(data); }, }); After making the ajax call, the data returned includes s ...

Having issues with indexing a duplicated array in VBA

Instead of only using the original arrays, I am facing a challenge with selecting from a variety of arrays before running this code. The following code snippet illustrates the issue at hand. It appears that there is a problem when trying to access a copie ...

Retrieving Information from a Multidimensional Array

I am currently utilizing the S3 library which can be found at this link: Although the library works effectively, I am encountering difficulties in extracting specific data from the array results it provides. When I retrieve the contents of the bucket, the ...

Issues with Datepicker functionality in Bootstrap 5 are causing it to malfunction or not display

I am having trouble incorporating a timepicker on my webpage with bootstrap 5. The calendar feature isn't loading properly, preventing me from selecting any dates. I'm unsure if the issue lies with an error on my end or if the plugin isn't c ...

Is there a way to simultaneously view and send this JSON data to the server using console.log?

I'm looking to inspect the JSON data being sent and received by the server, but I'm struggling to understand how promises work in this scenario. When I use console.log() on the function body, I see Promise { pending }. Unfortunately, I can' ...

Is there a way to refresh the list automatically after deleting an item using Firebase?

When I use ngFor on a list to display multiple recordings in a table, I have two methods in my TypeScript file - one for getAll and another for delete, as shown below: HTML: <tr *ngFor="let value of imagesList"> <td scope="row& ...

Clicking to rotate causes the model to disappear in OrbitControls.js

I have incorporated OrbitControls.js into my website to enable users to zoom in/out and rotate 3D models. However, I am encountering an issue where clicking anywhere on the page causes the model to disappear and disables the model switching buttons. Previo ...

Tips for using an array as a jQuery selector in JavaScript

Managing an element with an array id id="x[]" can be tricky when it comes to dynamically changing content based on database entries. This specific element is essentially a delete button for removing table rows from the database. <div align="center" id= ...

The compilation error occurred with the file named './__MACOSX/._request.py' while using Google Cloud

I'm currently attempting to utilize Cloud Functions in gcloud, however, I am encountering the following error: Build failed: *** Error compiling './__MACOSX/._request.py'... I'm having trouble figuring out the cause of this issue. (By ...

To insert a <div> element within a <tr> element while preserving the exact position of the <tr> tag - here's how you can do it:

I have a challenge with my table where I need to add a green progress bar in the form of a div element within a tr. The width of this progress bar should change dynamically from 0% to 100%, reflecting the current runtime of the video associated with that p ...

Steps to integrate the Save as PNG functionality in Vega using a customized menu

As I develop a data dashboard with Vega for visualizing outputs, I decided to customize the menu system by removing the actions dropdown. However, I still want to incorporate the "Save as PNG" option from the original dropdown (as shown in the image below) ...

Is it possible to maintain a fixed footer while utilizing async/ajax functions?

Looking for a reliable solution to have a fixed footer that adjusts based on the page content? I've tested multiple samples, but they all fall short when it comes to incorporating AJAX elements. Is there a fixed footer out there that truly works seaml ...

"Learn how to seamlessly submit a form and display the results without the need to refresh the

Here is the form and result div: <form action="result.php"> <input type="checkbox" name="number[]" value="11" /> <input type="checkbox" name="number[]" value="12" /> <input type="checkbox" name="number[]" value="13" /> <input t ...