Finding the mean value of elements in a JavaScript array

The JSON data contains the answers from three users:

[{"id":"1","user":"001","answer":"1,1,3,2,2,1,3,2"},
{"id":"2","user":"002","answer":"2,3,3,2,1,1,3,2"},
{"id":"3","user":"003","answer":"3,5,3,5,3,1,3,2"}]

To process this data using JavaScript and jQuery:

jQuery.ajax({
    url: "file.json",
    type: "POST",
    dataType: "json",
    async: false,
    success: function (data) {
    var averages = [];
    for (i = 0; i < data.length; i++) { 
        var sum = data[i].answer.split(',').reduce((acc, curr) => acc + parseInt(curr), 0);
        var average = sum / data[i].answer.split(',').length;
        averages.push(average);
    }
    console.log(averages);
});

This will calculate the average for each set of answers, resulting in these 8 average values:

2,3,3,3,2,1,3,2

Answer №1

function calculateAverage(arr) {
  return arr.reduce((a, b) => a + b, 0) / arr.length;
}
console.log(calculateAverage([10,20,30,40,50]));

Answer №2

generate a fresh array from the response and then calculate the total sum followed by division by its count

var newArray = [{
    "id": "1",
    "user": "001",
    "response": "1,1,3,2,2,1,3,2"
  },
  {
    "id": "2",
    "user": "002",
    "response": "2,3,3,2,1,1,3,2"
  },
  {
    "id": "3",
    "user": "003",
    "response": "3,5,3,5,3,1,3,2"
  }
];
newArray.forEach(function(item) {
  
  var itemArray = item.response.split(',');
  
  var averageValue = itemArray.reduce(function(prev, curr) {
    
    return +prev + +curr
    
  })
  console.log(averageValue / itemArray.length)


})

Answer №3

You have the option to utilize:


Example in Action:

let data = [{"id":"1","user":"001","answer":"1,1,3,2,2,1,3,2"},
            {"id":"2","user":"002","answer":"2,3,3,2,1,1,3,2"},
            {"id":"3","user":"003","answer":"3,5,3,5,3,1,3,2"}];

let result = data.map(o => {
  /* Splitting the string into an array using , as a delimiter */
  let a = o["answer"].split(",");
  /*
   * Returning the average of the array by first summing up using .reduce()
   * and then dividing by the number of elements in the array.
   */
  return a.reduce((a,c) => (Number(c) + a), 0) / a.length;
});

console.log(result);

Answer №4

After receiving the answer, the next step is to split it by commas and convert the values to numbers. This process creates an array for each answer, allowing you to iterate through and calculate the average by adding all the numbers together and dividing by the count (the length of the array).

Keep in mind that the values in the answers are strings, so ensure to change them to numbers before performing any arithmetic operations. Otherwise, you will end up adding characters instead of numerical values.

var data = [{"id":"1","user":"001","answer":"1,1,3,2,2,1,3,2"},
            {"id":"2","user":"002","answer":"2,3,3,2,1,1,3,2"},
            {"id":"3","user":"003","answer":"3,5,3,5,3,1,3,2"}]

var arr = [];
for (var i = 0; i < data.length; i++) {
  var d = data[i].answer.split(",");
  var sum = 0;
  for (var j = 0; j < d.length; j++) {
    sum += parseInt(d[j]);
  }
  arr.push(sum / d.length);
}
console.log(arr);

If you require the average of each individual value from the three sets of answers, a slight modification is needed. You will first need to add up the corresponding values from each set and then calculate the averages:

var data = [{"id":"1","user":"001","answer":"1,1,3,2,2,1,3,2"},
            {"id":"2","user":"002","answer":"2,3,3,2,1,1,3,2"},
            {"id":"3","user":"003","answer":"3,5,3,5,3,1,3,2"}]

var arr = [];
for (var i = 0; i < data.length; i++) {
  var d = data[i].answer.split(",");
  for (var j = 0; j < d.length; j++) {
    d[j] = parseInt(d[j]);
  }
  if (arr.length == 0)
    arr = d;
  else {
    for (var j = 0; j < d.length; j++) {
      arr[j] += d[j];
    }
  }
}
for (var i = 0; i < arr.length; i++) {
  arr[i] = arr[i] / data.length;
}
console.log(arr);

Please note: This method assumes that each set of answers contains an equal number of values.

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

Versatile route able to handle any request thrown its way

My Node.js app is up and running smoothly using the Express.js framework. All routes in my application are set to post routes, such as: app.post('/login', function(req, res){ //perform login validation }); app.post('/AppHomepage', fun ...

Exploring an ArrayList using a user-defined object

Hey there, I'm currently facing a problem in searching for a specific string within a multi-dimensional ArrayList. I am working on creating a text-based adventure game where players collect various items. Each item is defined with the following proper ...

PHP: Avoiding Loading Records with Null Fields into an Array

There are four select fields available for the user to choose countries from. These select fields are generated dynamically from a database, fetching options directly from it. function addDropMenu($countryNo) { $conn = new mysqli('localhost', & ...

Is NextJS on-demand revalidation compatible with Next/link?

https://nextjs.org/docs/basic-features/data-fetching/incremental-static-regeneration#on-demand-revalidation According to the NextJS documentation, it appears that on-demand cache revalidation should function properly with regular <a> tags and when t ...

Reducing the length of Javascript code

Recently, I have been working on a project where I needed to use a piece of Javascript code to insert text into an input element when its label is double-clicked. $(document).ready(function() { $('#name-label').dblclick(function(){ $ ...

Multiple executions can be triggered by ng-checked function

Here is the code snippet from the view : <input type="radio" name="tabset" id="tab2" aria-controls="rauchbier" ng-checked="switch_tabs()"> And in the controller, we have: $scope.switch_tabs = function(){ console.log(notificatio ...

Exploring the impact of JavaScript tags on website performance in accordance with W3

While researching website optimization strategies today, I came across an article discussing the benefits of moving JavaScript scripts to the bottom of the HTML page. I am curious if this approach aligns with W3C's recommendations since traditionally ...

Executing PHP scripts using Ajax

Check out the code snippet below: <?php //echo $this->Html->css(array('bootstrap', 'mark', 'style')); echo $this->Html->script(array('timer','swfobject','bootstrap.min.js')); // ...

Ways to verify the emptiness of a Gson JsonObject using the "isEmpty()" method

For my data manipulation needs, I decided to utilize the Google Gson API for generating JSON objects. Initially, I created a JsonObject instance with the following line of code: JsonObject json = new JsonObject(); Upon printing it out, I noticed that the ...

directive ng-click not responding

drawer-card.html (template) <div class="drawer-card-wrapper"> <div class="drawer-card-icon" ngClick="dcCtrl.toggle()"> <i class="icon--{{ icon }}"/> </div> <div class="{{'drawer-card ' + (classesToAdd || '&apo ...

Initiating communication with a web service API

I am struggling to retrieve data from a web service API and I can't seem to display anything. As a newcomer to AngularJS, I would greatly appreciate any assistance. Below is the controller and factory code that I am currently using: Controller app.c ...

What is the process for transforming the outcome of a Javascript function into a webpage containing solely a JSON string?

I have a specific requirement where I need to fetch a URL and ensure that the only content displayed on the page is a JSON string. For instance, let's say I created a basic function called getDayOfWeek() to determine the current day of the week. The ...

Obtain the identification numbers from the row within the table

I have a table displaying an email Inbox (see excerpt screenshot here). When the user clicks on a checkbox, I need to populate two dropdowns with the correct items. function fnHandleSelectCBClick(cb) { try { var tableRow = $(cb).parent().par ...

Dragging elements with jQuery to move them outside of a side panel

For a hidden panel, I am utilizing the script mentioned below. I have listed some boxes in the panel and attempted to drag them and drop them onto a workspace. This is a demonstration that works with HTML5. <a id="simple-menu" href="#sidr">Jobs< ...

What causes Webpack to overlook changes in React and HMR integration?

I am facing an issue while attempting to build my React project with Webpack using hot module replacement. Despite making changes to files, Webpack seems to ignore them. What could be the problem? Here is my configuration: var path = require('path& ...

What is the best way to increase the number of elements associated with a particular key in an

I am attempting to transform XML nodes into arrays, where I have 3 separate nodes within a parent match node that need to be converted into arrays. Upon executing the following code: foreach($lineup->away->player as $player){ $awaysquad .= $pla ...

Troubleshooting legacy components integration in Next.js (Error resolving 'react/jsx-dev-runtime' and issue with importing Global CSS files)

I've recently set up a fresh Next.js project (React v 17.0.1) and I'm trying to import components from an older project, but I'm running into some errors: Module not found: Can't resolve 'react/jsx-dev-runtime'. It seems like ...

Clicking on a JQuery element triggers an AJAX function, although the outcome is not aligned with the intended

Instead of using a fiddle for this task, I decided to work on it online since my knowledge of fiddles is limited. However, after multiple attempts and hours spent rewriting the code, I still can't get it right. The issue at hand requires that when cl ...

Ensure that the central section of the slider remains illuminated

Looking for help with customizing my "product" slider, lightSlider. I want the middle div to always be highlighted when navigating through the slider. Here's what it looks like currently: Link to screenshot - current. My goal is to achieve this look: ...

Uploading a file with AngularJS and storing it in a database

I have been attempting to implement ngFileUpload in order to upload images and store them in a database – specifically, a mongoLab database that accepts JSON objects which can be posted using this syntax: $http.post('myMongoName/myDb/myCollection/ ...