Calculating the mean value of an array containing objects with a single key-value pair in JavaScript

I have a list of users along with their ages, and I need to calculate the average age of all users. I initially attempted to use the reduce method for this task, but encountered syntax errors preventing successful implementation.

Below is the code snippet I used:

let sam = { name: "Sam", age: 21 };
let hannah = { name: "Hannah", age: 33 };
let alex = { name: "Alex", age: 24 };

let users = [sam, hannah, alex];

function getAverageAge(array){
  let sumAge = array.age.reduce(function(sum, current) {
    return sum + current;
  }, 0)

  return (sumAge / (array.length));
}

console.log(getAverageAge(users)); // Expected output: (21 + 33 + 24) / 3 = 26

The expected result in this case should be 26.

Answer №1

Objects have an `age` property, not arrays:

let john = { name: "John", age: 25 };
let emily = { name: "Emily", age: 30 };
let jacob = { name: "Jacob", age: 29 };

let people = [ john, emily, jacob ];

function getAverageAge(arr){
  const totalAge = arr.reduce(function(sum, current) {
    return sum + current.age;
  }, 0)

  return (totalAge / arr.length);
}

console.log( getAverageAge(people) );

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

What is the best way to achieve complete code coverage for ajax requests, including success and failure callbacks, using Jasmine and Blanket.js?

Here is a sample code snippet for adding a row: var Utils = {}; Utils.genericAddRowPost = function(url) { return $.post(url); }; Utils.genericAddRow = function(dataSource, url) { genericAddRowPost(url).done(function(data, textStatus, jqXHR) { ...

What happens when the loading state does not update while using an async function in an onClick event?

I'm currently working on implementing the MUI Loading Button and encountering an issue with changing the loading state of the button upon click. Despite setting the state of downloadLoading to true in the onClick event, it always returns false. The p ...

A pop-up box appears when hovering over a radio button

There are three radio button options available: None Float Left Float Right When the user hovers over the radio button, I want to show a preview of the div. <asp:radiobuttonlist runat="server" id="rbl" repeatdirection="Horizontal"> <asp:li ...

Importing data from text documents into a C array

Hey there, I have a question for you. How would you go about reading lines of text from a file, separating the words, and storing them in an array? Imagine if my text file contained these two lines: 1005; AndyCool; Andy; Anderson; 23; LA 1006; JohnCool; ...

Issue: Unable to locate 'path' in directory 'C:workdemo ode_modulesmime-types'

Encountering an error after updating from "react-scripts": "4.0.3" to "react-scripts": "5.0.1",. I need assistance with understanding why this error is occurring and how to resolve it... ERROR in ./node_modules/mime ...

The AngularJS HTTP interceptor is a crucial component for handling

Is there a way to use an interceptor in AngularJS to log "finished AJAX request" when any request is completed? I've been exploring interceptors and currently have the following setup, but it triggers at the beginning of the request rather than the e ...

Styling multiple Higher Order Components (HoCs) using Material UI withStyles

When developing my application, I encountered an issue with using Higher Order Components (HoCs) and withStyles for styling. If I apply multiple HoCs to one component, the classes prop of the first HoC gets passed to the next one in the compose chain, caus ...

Creating a basic bar chart using NVD3 with X and Y axes in AngularJS

I'm currently utilizing the nvd3.js plugin within my angular-js application. I have a straightforward task of creating a bar chart, where bars represent months along the x-axis and revenue values on the y-axis. My goal is to accomplish this using the ...

Encountering issues with formData in nextjs 13 due to incorrect data type

In my NextJS application, I am using the dataForm method to retrieve the values from a form's fields: export async function getDataForm(formData) { const bodyQuery = { ....... skip: formData.get("gridSkip") ...

Experiencing a blank page error when trying to render a partial view using Angular.js

Can someone assist me? I am encountering an issue where the partial view is not rendering properly using ui-router in Angular.js. Below is my code snippet. <!DOCTYPE html> <html lang="en" ng-app="Spesh"> <head> <meta charset="utf- ...

Unable to remove data once it exceeds 10 entries while using AJAX, jQuery, and JavaScript/PHP

I am having an issue where I can insert data into the first 10 rows and delete any of them successfully. However, when I try to insert data starting from the 11th row, I am unable to delete any rows past the 10th. UPDATE: The deletion function does not wo ...

Using DraftJS to swap text while preserving formatting

Currently, I am implementing Draftjs with draft-js-plugins-editor and utilizing two plugins: draft-js-mathjax-plugin and draft-js-mention-plugin My goal is to replace all mentions with their corresponding values when the user uses '@' to mention ...

Instructions on incorporating domains into next.config.js for the "next/image" function with the help of a plugin

Here is the configuration I am currently using. // next.config.js const withImages = require("next-images"); module.exports = withImages({ webpack(config, options) { return config; }, }); I need to include this code in order to allow images from ...

Arrange an assortment of random arrays in descending order

I have an assignment where I need to organize a set of random numbers in descending order. The random numbers are generated within a specific range and I need to find the index of the largest number and swap it to the first position, then the second larges ...

Is it possible to organize and filter a dropdown menu in JQuery based on a secondary value (new attribute)?

Can the drop-down list be sorted by value2? <select id="ddlList"> <option value="3" value2="3">Three</option> <option value="1" value2="1">One</option> <option value="Order_0" value2="0">Zero</option> </sele ...

Is there a more efficient method for transforming an HTML form into an object through serialization?

I'm in the process of creating a form that includes both radio and checkbox inputs. Since multiple elements share the same name, I have developed the following solution. Is there a more efficient and simpler way, using only pure JavaScript, to conver ...

loop through an array and use splice to select items and modify the array

My current issue involves working with a pixabay array. Although I successfully retrieved the data from my array, it contains 20 random pictures when I only need 3 to be displayed on my website. I attempted to use a slice array for this purpose, but unfor ...

Guide on merging two JSON objects in AngularJS

In my angular controller, I have the following code: var jsonOne = $cookies.get('test'); // console logs {"domain":"localhost","zip":33333} var jsonTwo = angular.toJson($scope.formData); // console logs {"id":"210","name":"sam"} var final = $. ...

Is it possible to send an entire HTML table to the server and then update the database table with it?

Recently, I encountered an issue that has me stumped. Suppose I have a database table A with multiple columns and the server (PHP script) renders this data into an HTML table for the web client. Now, the challenge lies in allowing users to add/delete rows ...

Displaying Multiple HighCharts on a single AngularJS page

As a beginner with HighCharts, I am working on adding two Highcharts to the same page that will access the same data source but display different pieces of data for each graph. For example, the categories will remain constant while the series[] will vary. ...