Tips for looping through an array of objects and summing their attributes

Here we have an array of objects as an example:

[{Name: Deji, Age: 12}, {Name: Sonia, Age: 13}, {Name: Fabio, Age: 21}]

I am curious about how to loop through this array in order to calculate the total age of all the people included.

Is there a specific function that can be used to sum up the ages of the individuals in the array?

Answer №1

Utilize the Array#forEach method along with Array#reduce to loop through array elements and accumulate the age of each player into your variable.

Using forEach:

const players = [{Name : 'Deji', Age: 12}, {Name : 'Sonia', Age: 13}, {Name : 'Fabio', Age: 21}];

let age = 0;

players.forEach(player => age += player.Age);

console.log(age);

Using reduce:

const players = [{Name : 'Deji', Age: 12}, {Name : 'Sonia', Age: 13}, {Name : 'Fabio', Age: 21}];

const age = players.reduce((sum, player) => sum + player.Age, 0);

console.log(age);

Answer №2

The JSON structure you provided is invalid. Here is the correct format:

[ { "Name": "Deji", "Age": 12 }, { "Name": "Sonia", "Age": 13 }, { "Name": "Fabio", "Age": 21 } ]

To calculate the total using AngularJS, you can utilize the array.reduce function.

DEMO

 angular.module('MyModule', [])
.controller( 'MyController', function($scope){
 $scope.data = [
  {
    "Name": "Deji",
    "Age": 12
  },
  {
    "Name": "Sonia",
    "Age": 13
  },
  {
    "Name": "Fabio",
    "Age": 21
  }
];    
$scope.sum = function(items, prop){
        return items.reduce( function(a, b){
            return a + b[prop];
        }, 0);
};
$scope.totalAges = $scope.sum($scope.data, 'Age');
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app='MyModule' ng-controller='MyController'>
    <p>totalAges = {{totalAges}}</p>
</div>

Answer №3

let students = [{Name : 'Alice', Age: 18}, {Name : 'Bob', Age : 20}, {Name : 'Charlie', Age: 22}];
let totalAge = 0;
students.forEach(function(person){
 totalAge += person.Age;
})
console.log(totalAge)

Iterate over each object using forEach, retrieve the Age property, and calculate the sum.

Answer №4

Give this a shot:

let students = [{Name : 'Deji', Age: 12}, {Name : 'Sonia', Age : 13}, {Name : 'Fabio', Age: 21}];

let totalAge = 0;
for(let student of students){
    totalAge += student.Age;
}

console.log(totalAge);

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

Can you create a dropdown menu using information from one JSON file and have the selected option come from another source?

Recently, I came across this JavaScript code that is supposed to create a dropdown list of statuses: $.getJSON('/statuses', { ajax: 'true' }, function (data) { var html; var len = data.length; html + ...

Navigate to a specific moment in an HTML5 audio track by clicking on the progress bar

<html> <head> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script> <script> $(document).ready(function(){ var counter = 0; ...

Send an array of data using AngularJS multipart form

I am struggling with an issue where I have an array of colors and sizes, along with other data such as product name and images. Despite being able to send image files and product names without any problems, attaching the color and size array leads to a 500 ...

The HTML image is not updating, the function does not appear to be triggering

My attempt to add a source to an image using JavaScript and some jQuery code I found online isn't working as expected: <html> <head> <script src = "http://www.example.com/images/"> var count=1; var initnumber=100 ...

Dynamic count down using JavaScript or jQuery

I am looking for a way to create a countdown timer that I can adjust the time interval for in my database. Basically, I have a timestamp in my database table that might change, and I want to check it every 30 seconds and update my countdown accordingly. H ...

Python array unpacking issue: requiring over 3 values

I recently started learning Python and I'm attempting to compare some values that are stored in an array. However, when I try to run my code, I encounter an error message that reads: ValueError: need more than 3 values to unpack. Here is my code: ...

Include criteria in my ajax call (conditional statements)

Is there a way to add conditions to my ajax request? Whenever I include the code below, it only seems to work for one item at a time. $.ajax({ type: 'GET', url: urlPost, success: function (data) { $.each(data, function (key, value) { ...

"Storing MySQL query results in a Java array: A step-by-step guide

I have come across tips online recommending storing the queried data in an ArrayList and then converting it into an Array. However, the code I currently have does not seem to be working as expected. The SQL syntax has been tested and is correct (tested i ...

Using JavaScript and TypeScript to create a regular expression that meets three different conditions

I need assistance validating a specific element in an XML document using regular expressions. <ConfigOption>value</ConfigOption> Here are the requirements for ConfigOption: Allowed characters include letters, numbers, underscores, and spaces. ...

Can you explain how to pause the .setInterval() function when hovering over it and clicking on the interior content simultaneously?

I have been working on a slideshow that involves building elements into an array, modifying the DOM, and using items from the array to fade in and out on a timer. While I have made progress, there are still a few things I would like to accomplish but I am ...

Is it necessary to specify the JavaScript version for Firefox? (UPDATE: How can I enable `let` in FF version 44 and below)

Our recent deployment of JavaScript includes the use of the let statement. This feature is not supported in Firefox browsers prior to version 44, unless JavaScript1.7 or JavaScript1.8 is explicitly declared. I am concerned about the potential risks of usi ...

Adjust the size of an array based on the specified index

I have an array defined as... let myArray = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] ...along with a starting index let start = 2 and an ending index let end = 5. I want to resize the array by taking elements from start to end, for example: start ...

Highlighting an Element Using Selenium Webdriver at Specific Coordinates

I'm currently in the process of automating a web application built with HTML5 using Selenium Webdriver. I need help figuring out how to highlight the exact coordinates where I have clicked on the Canvas element. For example, if I click on the Canvas a ...

Exploring the inner workings of the PHP array object

Recently, while utilizing a third-party software, I ran the print_r($_SESSION) command and received the following output: [stsco-portal_current_user] => UserIdentity Object ( [userName] => Gary [password] => [persiste ...

Issue with Navigation bar: Bootstrap menu fails to open upon clicking

My Bootstrap menu is experiencing an issue where it fails to open when I click on it. This means that I can't see any items in the menu. However, when I press the "Down key" on my keyboard, it opens immediately. This issue seems to occur specifically ...

What method can be used to verify if Handlebar.js is integrated into the application?

I am struggling to verify the presence of Handlebar JS on the application's HTML page. No matter what I do, it keeps throwing an error saying "Uncaught Reference Error - Handlebars is not defined". Can anyone provide guidance on how to fulfill this ta ...

Having difficulty using JavaScript regex to replace the middle of content?

I am working with a text name[one][1][two][45][text] Through this pattern, I am able to extract the number "45" /(.*?)rows\]\[([0-9]*)(.*)/; Now, my challenge is how can I change the only 45 to a different digit? Using the same pattern and re ...

I am struggling with sending post requests in Node.js

I am currently facing a challenge with handling form data from a webpage using Node.js and writing that data to a file. It seems like there might be an issue with how Node.js is processing my POST request, or perhaps the way I am sending the request from t ...

Controls that shift a DIV in either direction

I've been working on making a div scroll left or right with either a mouseover effect or click, but I can't seem to figure out what's going wrong. My initial attempt was straightforward: <body> <div id="innerscroll"></div> ...

Evaluate the functionality of an Angular controller method that interacts with the Document Object Model (

We currently have an AngularJS controller that contains the following function: $scope.testMe = function() { return $('#test'); } So, how can we effectively test this function? We attempted a Karma test as shown below: describe(' ...