What is the method for applying reduce to an array of objects in order to calculate the total value based on a specific property within each object?

I'm attempting to calculate the total population of males and females for each county. For example, if "Bomi" has both male and female populations, they should be combined. However, I'm struggling to get it to work properly.

let population = [{
            "county": "Bomi",
            "district": "Dowein",
            "male": 6589,
            "female": 6599
        },
        {
            "county": "Bomi",
            "district": "Klay",
            "male": 11884,
            "female": 11513
        },
        {
            "county": "Lofa",
            "district": "Senjeh",
            "male": 15442,
            "female": 14585
        },
        {
            "county": "Lofa",
            "district": "Suehn Mecca ",
            "male": 9025,
            "female": 8482
        }]

 let countyPopTotal = POPULATION.reduce(function(accumulator, currentValue, index) {
            if (accumulator.indexOf(currentValue.county) === -1) {
              let sum = 0;
               sum += currentValue.male + currentValue.female
                accumulator.push(sum)
            }
            return accumulator
        }, [])
        console.log(countyPopTotal);

Answer №1

Utilizing an Object rather than an Array to store the counts for various countries can simplify the process:

let countryStats = [{
            "country": "USA",
            "state": "California",
            "male": 25000,
            "female": 27000
        },
        {
            "country": "USA",
            "state": "Texas",
            "male": 35000,
            "female": 32000
        },
        {
            "country": "Canada",
            "province": "Ontario",
            "male": 18000,
            "female": 20000
        },
        {
            "country": "Canada",
            "province": "Quebec",
            "male": 15000,
            "female": 16000
        }]

 let countryPopulationTotal = countryStats.reduce(function(accumulator, current, index) {
            if (!accumulator[current.country]) accumulator[current.country]=0
            accumulator[current.country] += current.male + current.female
            return accumulator
        }, {})
        console.log(countryPopulationTotal);
 
 // Alternatively, for a more concise approach, everything can be condensed into a single line:
 let allTotals = countryStats.reduce((a,c)=>(a[c.country]=(a[c.country]||0)+c.male+c.female,a),{})
console.log(allTotals);

Answer №2

If you want to calculate the total population by gender in a specific county, you can utilize the Array.reduce method.

population.reduce((accumulator, value) => {
    const county = value.county;

    if (!accumulator[county]) {
        accumulator[county] = {};
    }

    const maleCount = accumulator[county].male || 0;
    const femaleCount = accumulator[county].female || 0;
    const updatedMaleCount = maleCount + value.male;
    const updatedFemaleCount = femaleCount + value.female;
    accumulator[county] = { male: updatedMaleCount, female: updatedFemaleCount, total: updatedMaleCount + updatedFemaleCount };

    return accumulator;
}, {})

The resulting output will be similar to:

{
    "Bomi": {
        "male": 18473,
        "female": 18112,
        "total": 36585
    },
    "Lofa": {
        "male": 24467,
        "female": 23067,
        "total": 47534
    }
}

You can easily retrieve any of these computed values afterward.

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

Is there a way to modify the appearance of a block element and transmit a parameter to a PHP function?

It might seem like I'm overthinking things, but I am trying to achieve two goals with the HTML code provided. First, when a user selects an option, I want to toggle the display style of the leaderTable from hidden to visible if it meets certain criter ...

The controller is unable to retrieve the posted value

Whenever I try to retrieve the post value from my controller, it always returns null. Even though I can see that there is a post value present when I check, for some reason, I am not able to access that value in my controller. Does anyone know what the p ...

What is the process for setting a default value in an array using Angular and then showcasing that value in a textbox?

I have been working on creating a form that includes a feature to dynamically append new rows. While I am able to successfully create new rows dynamically, I am facing an issue with displaying the initial values in my textboxes. Below is a snippet of my c ...

ever-evolving background-image with dynamic CSS styling

Being new to both PHP and Javascript, please excuse any mistakes in my explanation. I have information stored in a PHP array that I bring to my index page using the function below (located in a separate file called articles.php that is included in my index ...

An error occurred: Cannot access the 'splice' property of an undefined value

//Screenshot <div v-for='(place) in query.visitPlaces' :key="place.name"> <div class="column is-4 is-narrow"> <b-field label="Nights"> <b-input type="text" v-model="place.nights" placeho ...

Executing asynchronous jQuery AJAX requests using the async/await syntax

Currently, I have a situation where I am using 3 ajax call methods in succession. However, there needs to be a delay between the second and third ajax calls. Initially, I used "async:false" in the second ajax call and everything worked smoothly. But later ...

Is it possible to pass multiple IDs into document.getElementById?

I am working on a form that contains 45 dropdown lists and currently, I am using the following code for validation. Is there a way to modify this code so that I can use a single function to validate all 45 dropdown lists? Below is the Function: function ...

Assigning a value to a variable using conditional IF statements and the Alert function in JavaScript

How can I set a variable value based on conditions and display an Alert in JavaScript? Hello, I have a code that utilizes Alerts to display the results of evaluating the visibility status of two controls using jQuery. If pnlResultados is visible, it will ...

Using conditional binding with AngularJS, the value will only be concatenated and bound if the property is not empty

As a beginner with Angular, I am attempting to link a string to a model as long as the value is not empty. This is successful for a single input, but I now want to merge multiple text inputs into a single string. <input type="text" ng-model="data.sou ...

Struggles with loading order in Knockout.JS

I've encountered an issue with loading my scripts properly for a page utilizing a knockout.js form. Upon page load, my viewmodel js file isn't immediately loaded, resulting in errors that cause the validation messages to flash and hidden divs to ...

Experiencing Strange Issues with Jquery Image Carousel... Assistance Needed!

I recently created a jquery slideshow using a tutorial I found at this link: While the slideshow is functioning correctly for the most part, there is a strange issue that occurs right at the beginning when displaying the first image. Initially, the first ...

Learn the process of retrieving JSON data in an Excel file using the json_to_sheet function

I am currently working on populating an excel file by utilizing the JSON data provided below. This JSON data is retrieved from an HTTP response and I intend to utilize it for downloading an excel file. { "dynaModel":[ { ...

Can the getState() method be utilized within a reducer function?

I have encountered an issue with my reducers. The login reducer is functioning properly, but when I added a logout reducer, it stopped working. export const rootReducer = combineReducers({ login: loginReducer, logout: logoutReducer }); export c ...

`Cannot press when using custom cursor in JS?`

Hey there! I'm currently working on implementing a custom cursor for specific elements on my website. However, I've encountered a little hiccup - once the custom cursor is in place, I'm no longer able to click on any elements. Does anyone ha ...

Node JS | Error: Unable to access the property 'first_name' of an undefined object

Just getting started with my MEAN application and I've hit a roadblock while trying to add data to the database. Can someone please help me find a solution for this? This is the main file, the entry point of the application. //Importing modules var ...

Retrieving information from a GET request/JSON payload

It's been a while since I last worked with JavaScript and I'm struggling to figure out how to extract data from a JSON object. Currently, I am making a simple GET request to the Giphy API in order to retrieve URLs from the response, but for some ...

Displaying markers on a Google map by fetching data from a MySQL database in PHP

The image attached here serves as an example. You can view it here. Currently, I display locations on a map in an HTML page with static code like: Here is the JavaScript code to load the map on the page: <script type="text/javascript" src="https://ma ...

How to automatically refresh the idToken in a Firebase http request when the currentUser object is null?

Currently implementing a Custom Auth System with React JS and Firebase for sign-in operations. The Back End generates a custom token, allowing the Front End to execute signInWithCustomToken. After successful sign in, an issue arises when refreshing the pa ...

Error encountered while attempting to save process using ajax - 500 Internal Server Error

I am facing an issue with my CodeIgniter code where I encounter a 500 internal server error when trying to save data. I am not sure why this problem is happening and would appreciate any help. Below is the AJAX code in the view: function save() { $(& ...

Can a client receive a response from server actions in Next.js 13?

I'm currently developing a Next.js application and I've created an action in app/actions/create-foo-action.js. In this server action, I am attempting to send a response back to the client. import { connectDB } from "@utils/database" imp ...