Tips for invoking a reduce mechanism within a separate function

I need assistance with implementing a reduce function:

users.reduce(function (acc, obj) { return acc + obj.age/3; }, 0);   

within the following function structure:

function calculateUserAverageAge(users) {};

To analyze this array of objects and calculate the average of their "age" values:

const users = [{
           name: 'Brendan Eich',
           age: 56,
         }, {
           name: 'Linus Torvalds',
           age: 48,
         }, {
           name: 'Margaret Hamilton',
           age: 81,
         }];

Your guidance and support are greatly appreciated!

Answer №1

Simply reorganize your code within the function and then return the result.

Important: Instead of using 3, opt to use users.length instead.

In my opinion, it makes more sense mathematically to divide by the total number after summing them up, rather than dividing at each iteration.

const users = [{
  name: 'Brendan Eich',
  age: 56,
}, {
  name: 'Linus Torvalds',
  age: 48,
}, {
  name: 'Margaret Hamilton',
  age: 81,
}];

function computeUserAverageAge(users) {
  return Math.round(users.reduce((acc, obj) => acc + obj.age, 0) / users.length);
};

console.log(computeUserAverageAge(users))

Answer №2

It seems like the solution lies in returning the result of the reduce function. Using arrow functions can help simplify the code:

const getUserAverageAge = users => users.reduce((sum, { age }) => sum + age, 0) / 3;
console.log(getUserAverageAge(
  [{
    name: 'Brendan Eich',
    age: 56,
  }, {
    name: 'Linus Torvalds',
    age: 48,
  }, {
    name: 'Margaret Hamilton',
    age: 81,
  }]
));

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

Setting compilerOptions.isCustomElement for VueJS 3 in a Laravel project: A step-by-step guide

I am currently working on integrating VueJS 3 into a Laravel project and utilizing a JS file to implement a markdown toolbar. The JS file contains functions that generate buttons for applying various markdown options. Everything is functioning properly, bu ...

When the div is loaded, automatically navigate to the crucial li element within it, such as the one with the class "import

Welcome to my first webpage: <html> <head> <script type="text/javascript" src="js/jquery.min.js"></script> </head> <body> <div id="comment"></div> <script type="text/ja ...

Trigger a function post-rendering in a React component

Hey everyone, hope you're having a great day! I've been diving into React for a few months now. I'm making an effort to steer clear of using the traditional React Components, opting instead for React Hooks. However, there are instances wher ...

HTTP request form

I'm currently working on a form that utilizes XMLHttpRequest, and I've encountered an issue: Upon form submission, if the response is 0 (string), the message displayed in the #output section is "Something went wrong..." (which is correct); Howe ...

Unusual behavior of .replace() function observed in Chrome browser

<div> <input type="text" class="allownumericwithdecimal"/>saadad </div> $(".allownumericwithdecimal").live("keypress keyup ", function (event) { $(this).val($(this).val().replace(/[^0-9\.]/g, '')); var text = ...

The entire DOM has been seamlessly replaced by React.JS within the Node.js server

I am currently focusing on practicing the MERN structure, so my goal was to start by setting up a node.js server and react front-end. However, I encountered an issue where the entire DOM gets overwritten once the server is fired up. This has left me wonde ...

What is the optimal number of parameters in JavaScript?

After stumbling upon a question on StackOverflow discussing the number of parameters in JavaScript functions (How many parameters are too many?), I started pondering if there is a real limitation on how many parameters a JS function can have. test(65536 ...

What could be causing my search function to not recognize special characters?

It seems like there might be an issue with character encoding. My JavaScript search function is unable to identify specific strings that contain certain special characters such as parentheses, asterisks, and numbers. The JavaScript code I am using is quit ...

The Ajax call failed to connect with the matching JSON file

<!DOCTYPE html> <html> <body> <p id="demo"></p> <script <script> function launch_program(){ var xml=new XMLHttpRequest(); var url="student.json"; xml.open("GET", url, true); xml.send(); xml.onreadystatechange=fun ...

To effectively utilize the expect function in testing, should you use it over softAssertAll or find a way to explicitly display in the test results that the softAssertAll has successfully passed? (Error

Utilizing the 'soft-assert' library (soft-assert library) allows me to implement assertions in my test steps without halting the entire test if any of them fail. While softAssertAll() command works effectively to verify all soft-assert at the en ...

creating an audio streaming application using child processes in nodejs

How can I effectively send a stream to a child process for streaming audio from a client to a server? I have successfully obtained the audio stream from a client. const ss = require('socket.io-stream'); const socketIo = require('socket.io& ...

Retrieve the customized attribute from the chosen option within the datalist

Is there a way to retrieve the custom attribute "location" of an option selected from a datalist and display it? I understand that for a select element we can use selectedIndex, but how can this be achieved with datalist? <!DOCTYPE html> <html&g ...

JavaScript - Changing the position of an item within a JSON object

I have implemented JQuery sortable to rearrange items in a JSON object into a JSON array. Let's assume we have the following JSON file: [ { "ID_id": "I3Y0RAmsr5", "DT_createdAt": "2020-12-02T14:39 ...

Why is the console log not working on a library that has been imported into a different React component?

Within my 'some-library' project, I added a console.log("message from some library") statement in the 'some-component.js' file. However, when I import 'some-component' from 'some-library' after running uglifyjs with ...

Having trouble with Mongoose's findOne method not functioning as expected

I am developing an application where users can input data such as the number of hours they slept and their eating habits. This information is then stored in a collection known as the Journal. When a user clicks on "stats", it activates a function called f ...

Error: The OOP class value for translateX in the Web Animation API is returning as undefined

I'm currently working on a basic animation project using JavaScript. I have utilized the Animation class from the Web Animation API. My goal is to create multiple instances of this class in order to animate different elements with varying values and r ...

Setting a radio button as default based on a variable value can be accomplished by following a few

I am working with 2 radio buttons and I need to dynamically check one based on a variable value. <input type="radio" name="team" id="team_7" value="7"> <input type="radio" name="team" id="team_8" value="8"> The variable number is set dependin ...

What is the purpose of using defer="defer" in JavaScript?

I've been experimenting with Three.js and found that it only functions properly when used like this: <script src="script.js" defer="defer"></script> However, I'm puzzled as to why the defer="defer" attribute is crucial... Can anyon ...

How to choose `optgroup` in Vue 1.x

In previous iterations of vue.js, developers had the ability to generate a dynamic select list utilizing optgroups similar to the example found here. In the latest versions of vue, the documentation suggests using v-for within the options instead of optgr ...

Troubleshooting: Issue with Updating Prototype Ajax Function

I am currently utilizing Prototype within the pylons framework and attempting to execute an Ajax call. Below is the structure of my html: <form method="POST" action = "javascript:void(0)" onsubmit = "new Ajax.Updater('graph','/saffron_m ...