What are the steps to grouping, summing, and calculating the average in a JavaScript array?

I have an array of objects

 const users = [
     { group: 'editor', name: 'Adam', age: 23 },
     { group: 'admin', name: 'John', age: 28 },
     { group: 'editor', name: 'William', age: 34 },
     { group: 'admin', name: 'Oliver', age: 28' }
 ];

The desired outcome is:

//sum
 sumAge = {
 editor: 57,  // 23+34
 admin: 56    // 28+28
}

//average
avgAge = {
   editor: 28.5,  // (23+34) / 2
   admin: 28    //(28+28)/2
}

To achieve this, I utilized the reduce() method to group objects in the array by 'group' and calculate the total age:

let sumAge = users.reduce((group, age) => {
    group[age.group] = (group[age.group] || 0) + age.age || 1;
    return group;
}, {})
console.log('sumAge', sumAge); // sumAge: {editor: 57, admin: 56} 
done!

How can we group objects of the array by the key 'group' and calculate the average age? I attempted:

let ageAvg= users.reduce((group, age) => {
      if (!group[age.group]) {
      group[age.group] = { ...age, count: 1 }
         return group;
      }
      group[age.group].age+= age.age;
      group[age.group].count += 1;
      return group;
      }, {})
const result = Object.keys(ageAvg).map(function(x){
     const item  = ageAvg[x];
     return {
         group: item.group,
         ageAvg: item.age/item.count,
     }
 })
console.log('result',result);
/*
result=[
    {group: "editor", ageAvg: 28.5}
    {group: "admin", ageAvg: 28}
]

However, the expected outcome is:

result = {
   editor: 28.5,  // (23+34) / 2
   admin: 28    //(28+28)/2
}

Answer №1

To find the total of age groups, you can utilize the reduce method.

For calculating the average based on the total, use Object.keys with length to create a new object using the getAvg function.

Check out this demonstration:

const users = [{
    group: 'editor',
    name: 'Adam',
    age: 23
  },
  {
    group: 'admin',
    name: 'John',
    age: 28
  },
  {
    group: 'editor',
    name: 'William',
    age: 34
  },
  {
    group: 'admin',
    name: 'Oliver',
    age: 28
  }
];

const sumId = users.reduce((a, {
  group,
  age
}) => (a[group] = (a[group] || 0) + age, a), {});

console.log(sumId); //{editor: 57, admin: 56}

//Average
const getAvg = (x) => {
  const item = {}
  const count = Object.keys(x).length
  Object.keys(x).map(function(y) {
    item[y] = sumId[y] / count
  })
  return item
}
console.log(getAvg(sumId)); //{editor: 28.5, admin: 28}

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

saving data in an array using JavaScript

I have a requirement to store values into an array in HTML that are generated by a random number generator in Python as {{player.a1s1}}. I have successfully handled this part. Essentially, every time the button "mm1a" is clicked, a new button will be displ ...

Attempting to clear the value of a state property using the delete method is proving to be ineffective

Within my React-component, there exists an optional property. Depending on whether this property is set or not, a modal dialog is displayed. Therefore, when the modal should be closed/hidden, the property must not be set. My state (in simplified form): i ...

Trim the name property of an object within an object's map function if it exceeds a certain length

Imagine having an object structured like this: var fullObj = { prop1: "myProp1", subobject: { Obj1_id: { id: "Obj3_id", name: "./", otherProperties:... }, Obj2_id: { id: "Obj2_id&q ...

Discovering the specific value within an array of various objects through Angular

Within a list of objects, I am specifically looking to extract the name "sample 4" from the second set of objects with an ID of 2. How can this value be retrieved using JavaScript or Angular? {Id: 1, name: sample 1, code: "type", order: 1} {Id: 1, name: ...

Trigger AngularJS functionality upon the completion of loading a Partial routed by Express

I'm fairly new to AngularJS and recently ran into an issue that's been keeping me up at night... Our application is built on node.js and express, with all partial routing handled by Express. The problem I'm facing is this: Whenever I load ...

What is the best way to display all divs once more after all filter-checkboxes have been unchecked?

I created a custom filter that displays board games based on the number of players and playing time selected through checkboxes. Initially, the filter works as intended when first loaded and used. However, I encountered an issue where if all checkboxes are ...

Troubleshooting: Mongoose Array Object Order Modification Issue

Imagine we have a person named Michael who lists his favoriteFruits as [ { name: 'Apple'}, {name: 'Banana'} ] The challenge at hand is to change the order of his favorite fruits. In other words, we want to transform it from: [ { name ...

The close button on bootstrapselect is oversized

Having an issue with implementing the bootstrap select search and close button in my view. An image has been uploaded through the following link: View the bootstrap select dropdown image here Javascript $('#class_list_for_fee_report').multisel ...

Inject a combination of HTML and JavaScript code into the Selenium Webdriver

I am facing a challenge where I have an HTML document stored in memory as a string, and it includes a <script> tag with a script that manipulates the DOM. My goal is to load this HTML page into Selenium WebDriver and retrieve the modified version aft ...

Can a C# MVC List<int> be transformed into a JavaScript array?

Can a MVC C# List be converted to a JavaScript array? var jsArray = @Model.IntList; I would really appreciate any assistance on this matter. ...

Adjust Text to Perfectly Fit Button

I am developing a quiz using bootstrap and javascript. One issue I encountered is that the text in the buttons can sometimes be longer than the button itself. This results in the text not fitting properly within the button, making it unreadable on mobile ...

Passing numerous arrays within multiple arrays using AngularJS

What is the process for sending this data in AngularJS? It consists of a multiple array within another multiple array that needs to be sent as one Object. [{ "working_day":"sunday", "from_time":{"hour":"9","min":"30"}, "to_time":{"hour":"6","min":"30"} }, ...

Retrieve the text inside the DIV that contains the clicked link

I'm facing an issue with my JS code: $(document).on("click", '.like', function (e) { $(this).parent().html("<a href = '#' class = 'unlike'><div class = 'heart'></div></a>"); ...

I'm curious why I can only see the HTML code and not the three.js code as well

I attempted to run a sample three.js game today, but only the HTML code appeared. I've also installed three.js with npm and tried running it with the VSC Live Server, but it's not working. You can find the source code here. What should be my nex ...

How to effectively sum values from another data frame based on two specific variables using a loop in R

Hey there! I've been struggling to create a loop that will add up the values in a specific column based on a given date and variable, and then place that sum in a designated spot within the data frame. So far, all my attempts at writing this loop hav ...

breezejs: Non-scalar relationship properties cannot be modified (Many-to-many constraint)

Utilizing AngularJS for data-binding has been smooth sailing so far, except for one hiccup I encountered while using a multi-select control. Instead of simply adding or removing an element from the model, it seems to replace it with a new array. This led t ...

Evaluate the array's components for any recurring elements within the string

I am currently facing an issue where I need to compare elements in an array with a string. I have two arrays and I want to check if any of the elements in those arrays are present in the given string. let resultString = "STEREON10.000 4ailthameGrinreD N ...

Persisting a single module using vuex-persistedstate

Is there a way to configure vuex-persistedstate so that only one module persists state through page refresh? Currently, when I use plugins: [createPersistedState()] inside the user module, it does not work. plugins: [createPersistedState()] only works wh ...

The GetJSON function is designed to fetch the entire array of data, without selectively retrieving specific

Below is the implementation of my GetJSON method: $(document).ready(function () { $.getJSON("/user", function (obj) { $.each(obj, function (key, value) { $("#usernames").append(value.firstname); console.log(ob ...

Apologies, the system encountered an issue while trying to access the "name" property which was undefined. Fortunately, after refreshing the page, the error was successfully resolved

When the profile route is accessed, the code below is executed: import React, { useState, useEffect } from 'react' import { Row, Col, Form, Button } from 'react-bootstrap' import { useDispatch, useSelector } from 'react-redux' ...