Feeling lost on how to utilize .map, .reduce, or foreach in my code

Recently delving into JavaScript, I find myself a bit perplexed despite scouring through various answers and resources on Mozilla.org. My struggle lies in seamlessly using .map and .filter on straightforward arrays, but feeling a bit lost when it comes to arrays containing objects.

For instance, I need to calculate the total sum of all ages in a given array.

I understand that .map creates a new array, which is not what I need in this scenario, .filter is used to return elements based on a specific condition, and forEach doesn't return any values.

Although I am restricted from using a for loop, it seems like the most practical solution in this case. (The code snippet below is accurate and functional).

Are there any alternative methods to approach this issue?

const users=[
  {firstName:"john",lastName:"Biden",age:26},
  {firstName:"jimmy",lastName:"cob",age:75},
  {firstName:"sam",lastName:"lewis",age:50},
  {firstName:"Ronald",lastName:"Mathew",age:26},  
];
var total=0
//console.log(users.length)
for(let i=0;i<users.length;i++){
    //console.log(users[i].age)
   total+=users[i].age
}

console.log(total)

Answer №1

Utilize the forEach method in place of a traditional for loop

Employ the map function to create an array of ages and then utilize reduce to calculate the sum

Use filter to specifically target individuals who are 50 years old or above

The ({age}) statement utilizes destructuring to extract only the age property from the array of objects, offering an alternative to

total=users.map(item => { return item.age })


            const users=[
            {firstName:"john",lastName:"Biden",age:26},
            {firstName:"jimmy",lastName:"cob",age:75},
            {firstName:"sam",lastName:"lewis",age:50},
            {firstName:"Ronald",lastName:"Mathew",age:26},  
            ];

            // Initializing total is required for forEach

            let total=0
            users.forEach(user => total+=user.age)
            console.log(total)

            // Map combined with reduce (for sum) does not require initialization

            total=users.map(({age}) => age)
            .reduce((a,b) => a+b)
            console.log(total)

            // Filter combined with reduce also does not require initializing the total

            let total50Plus=users.filter(({age}) => age>=50)
            .reduce((a,b) => a.age+b.age)   // No need for initializing an accumulator
            console.log(total50Plus)

            // The standard reduce initializes the accumulator at the end of the function

            total=users.reduce((acc,{age}) => acc+=age,0);  
            console.log(total)

            // Complete version 

            total=users.reduce((accumulator, current) => {
              accumulator += current.age;
              return accumulator;
            },0); // Initialize the accumulator 
            console.log(total)
          
        

Answer №2

Utilizing the ForEach method can greatly simplify the manipulation of your array of objects. It is important to grasp the parameters used in the forEach callback:

currentValue (user)

Refers to the current value of the element being processed in the array.

optional index

Represents the index of the current element being processed in the array.

optional array

Denotes the array to which forEach() is being applied.

Below is an example showcasing how to use forEach for achieving your desired outcome.

const users = [
  {firstName:"john",lastName:"Biden",age:26},
  {firstName:"jimmy",lastName:"cob",age:75},
  {firstName:"sam",lastName:"lewis",age:50},
  {firstName:"Ronald",lastName:"Mathew",age:26},  
];

let total = 0;

users.forEach(function(user, index, array) {
    total += user.age;
});

console.log(total);

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

Execute the command "prisma migrate dev" to update the existing database

I'm currently in the process of configuring Prisma migrate on a pre-populated MySQL database in my development environment, but I'm facing challenges getting it to function correctly. 1. After executing prisma db pull successfully to generate th ...

jQuery: add to either element

What is the most efficient way to use .appendTo for either one element or another based on their existence in the DOM? For instance, I would like to achieve the following: Preferred Method: .appendTo($('#div1') || $('#div2')); Less ...

Is there a way to transfer the data from a chosen row into a different table?

My task involves using a table with two different conditions. In the first table, I display all incoming data. Then, in the second table (referred to as "select summary"), I want to show the row selected in the first table. To achieve this, I am utilizing ...

"Browser compatibility issues: 404 error on post request in Firefox, while request is

When following this tutorial on React and PostgreSQL, the app should display the JSON fetch in the bash terminal around the 37-minute mark. However, there seems to be a problem as there is no feedback showing up on the npm or nodemon servers. After tryin ...

I'm having trouble locating the module "script!foundation-sites/dist/foundation.min.js on Heroic."

This is the content of my webpack.config.js file: var webpack = require('webpack'); var path = require('path'); process.env.NODE_ENV = process.env.NODE_ENV || 'development'; module.exports = { entry: [ 'script!jque ...

Creating dynamic elements in JavaScript and assigning them unique IDs

Hi there, I'm currently working on a project that requires generating dynamic divs with a textbox and delete button inside each one. The challenge I'm facing is figuring out how to assign a unique ID to each textbox element so that I can properly ...

JQuery failing to trigger AJAX function

I'm struggling with what seems like a simple issue and it's driving me crazy. The problem lies in this straightforward section of the website. I have a .js file that uses ajax to save a post into the database when the submit button is clicked. A ...

Are there any JavaScript libraries available that can mimic SQLite using localStorage?

My current application makes use of SQLite for storage, but I am looking to switch it up to make it compatible with Firefox and other browsers. I've been considering localStorage as an option. However, I've noticed that localStorage lacks some o ...

What is the best way to incorporate multiple HTML buttons that utilize the same JavaScript function within looped results?

My HTML page contains the following codes: <input type="text" class="woocommerce-Input woocommerce-Input--text input-text" name="metin" placeholder="Geben Sie Artikel Nr" style="width: 30%;"/><br/><br/> <input type="button" class="sin ...

ng-repeat isn't displaying the data

I have always been comfortable using the ng-repeat in Angular, but this time I seem to be facing a problem. I am trying to populate my DOM with data from a JSON file, but for some reason, the fields are not displaying as expected. Is there something wrong ...

"Encountering a Dojo error where the store is either null or not recognized

I encountered an issue with the function I have defined for the menu item "delete" when right-clicking on any folder in the tree hierarchy to delete a folder. Upon clicking, I received the error message "Store is null or not an object error in dojo" Can s ...

Scripts fail to load randomly due to RequireJs

I have obtained an HTML template from a platform like Themeforest, which came with numerous jQuery plugins and a main.js file where all these plugins are initialized and configured for the template. I am now in the process of developing an AngularJS applic ...

Why is it that every time I press the play button, nothing happens?

When I try to click on the play button, it does not start playing. I suspect there is something that needs to be adjusted in the javascript. Can someone please assist me in fixing this issue? Link to the example View Screenshot <script> (functio ...

The jQuery code functions properly only if it is inserted directly into the console

I'm facing an issue with a Mobile Font markup switch function. It works fine in the console, but not when I run it within a document ready function or call the function separately. It's strange that I have to paste the code directly into the con ...

Attach an event listener to the HTML content

Being new to Javascript, I am attempting to add an event listener for each button on every card. However, the code seems to only apply the event 'click' to the last card (button). Is there a way to make this work with the innerHTML of the card? l ...

Deployment to Amazon Amplify encounters failure when using Next JS

I've been encountering continuous failures while trying to deploy an SSG app on Next JS. The build consistently fails, and I'm met with an error message. Despite following the deployment documentation for SSG sites on Amazon diligently, the error ...

Trouble with Component Lifecycle (ComponentDidMount) activation while switching tabs in TabBar?

After implementing the react-native-tab-navigator library to navigate between components, I encountered an issue where the componentDidMount lifecycle method works only once. I have reached out for help by posting a query on Github and have also attempted ...

Is it possible to receive live updates from a MySQL database on a webpage using node.js and socket.io?

I've been following a tutorial that teaches how to receive real-time updates from a MySQL database using Node.js and Socket.io. Check it out here: Everything seems to work fine on the webpage. I can see updates in real-time when I open the page on tw ...

What is the best way to create a page that moves on release using HTML/CSS?

I'm working on a website where I want to make an interactive feature. When users click on an image on the left side of the page, I want the page to move backward. Similarly, when they click on an image on the right side, I want the page to move forwar ...

Transforming a JSON into a JavaScript object using deserialization

Within a Java server application, there exists a string that can be accessed through AJAX. The structure of this string is exemplified below: var json = [{ "adjacencies": [ { "nodeTo": "graphnode2", "nodeFrom": "graphnode1" ...