Determine the mean of each group of n elements within a given array

I am looking for assistance with a coding challenge involving an array of numbers. The goal is to calculate the average of every 3 elements in the array and store these averages in a new array.

Below is the code I currently have:


var total = 0;
//Array containing the numbers
for(i=0; i < arr.length; i++) {
    total += arr[i];
}

var avg = total / arr.length;
avgArray.push(Math.round(avg));

However, this code only gives me the average of all the elements in the array. I need help modifying it so that it calculates the average of every set of 3 elements instead.

For example, the avgArray should display: - Number 1: Average of first 3 elements - Number 2: Average of the second 3 elements - Number 3: Average of the third 3 elements ... Can you please provide guidance on how to achieve this?

Answer №1

When approaching this problem from a functional perspective, rather than procedural, one possible solution is:

function calculateAverage(arr, n) {
  if (!arr || !n){
    return false;
  }

  let groups = [];

  while (arr.length) {
    groups.push(arr.splice(0, n));
  }

  return groups.map(
    group =>   group.reduce(
      (a, b) => a + b
    ) / group.length
  );
}

console.log(
  calculateAverage([1, 2, 3, 4, 5, 6], 3)
); // [2, 5]

If you wish to round the average values, you can modify the console.log() statement as follows:

console.log(
  calculateAverage([1, 2, 4, 5, 6, 7], 3).map(Math.round)
);

Alternatively, the function itself can be adjusted to return rounded averages right away:

function calculateAverage(arr, n) {
  if (!arr || !n) {
    return false;
  }
  let groups = [];
  
  while (arr.length) {
    groups.push(arr.splice(0, n));
  }
  
  return groups.map(
    group => Math.round(group.reduce(
      (a, b) => a + b
    ) / group.length)
  );
}

console.log(
  calculateAverage([1, 2, 4, 5, 6, 7], 3)
);

For additional information and references regarding JavaScript functions used in these solutions, refer to the following:

Answer №2

One way to approach this problem is by creating a function that takes an array and batch size as parameters. The function then calculates the total sum of each batch based on the given size, and divides it by the batch size to determine the average for each group.

function computeGroupAverage(arr, n) {
  var result = [];
  
  for (var i = 0; i < arr.length;) {
    var sum = 0;
    
    for(var j = 0; j< n; j++){
      // Check if value is a number. If not, default to 0
      sum += +arr[i++] || 0
    }
    
    result.push(sum/n);
  }
  
  return result;
}

var arr = [1, 3, 2, 1, 5, 6, 7, 89,"test", 2, 3, 6, 8];

console.log(computeGroupAverage(arr, 3));
console.log(computeGroupAverage(arr, 2));

Answer №3

give this a shot

var numbers = [10, 20, 30, 40, 50, 60];
var averages = [];
total = 0;
for (var j = 0; j < numbers.length; j++) {
  total = total + numbers[j];
  if ((j + 1) % 3 == 0) {
    averages.push(total / 3);
    total = 0;
  }
}
console.log(averages);

Answer №4

To keep track of the count, simply create a variable called 'counter' and increase its value with every loop iteration.

var counter;

for ...
conuter++;
if(counter % 3 === 0)
  // perform certain actions

Answer №5

To achieve this, you can utilize the functions reduce() and map().

var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
var count = 0

var average = numbers.reduce(function(result, element, index) {
  if(index % 3 === 0) count++
  result[count] = (result[count] || 0) + element / 3
  if(index === numbers.length - 1) result = Object.keys(result).map(e => result[e])
  return result;
}, {})

console.log(average)

Answer №6

Instead of providing a code snippet, let's delve into the rationale behind the code. One approach they took was to only calculate and add the average value after every third iteration. This was achieved by utilizing a counter variable and checking if it is divisible by 3 with the modulo operator:

if (counter % 3 == 0)
  {calculate and add the average}

By evaluating whether the counter is divisible by 3 using the modulo operation, any action can be triggered specifically when the counter is a multiple of 3.

Answer №7

To calculate the average of every third element in an array, first add up the values and then divide by the count.

var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
    nth = 3,
    avg = array.reduce(function (r, a, i) {
        var ii = Math.floor(i / nth);
        r[ii] = ((r[ii] || 0) + a) / (i % nth !== nth - 1 || nth);
        return r;
    }, []);

console.log(avg);

Answer №8

Take a look at this unique tail call recursive method for some added variety:

let         numbers = Array(20).fill().map(_=> ~~(Math.random()*20)),
groupAverage = (arr, size, index=0, result=[]) => arr.length-index > 0 ? groupAverage(arr, size, index+size, result.concat(arr.slice(index,index+size).reduce((prev,current,_,source) => prev+current/source.length,0))) : result;
console.log(JSON.stringify(numbers));
console.log(JSON.stringify(groupAverage(numbers,3)));

Answer №9

Have you thought about using a for loop, but this time incrementing by 3 each iteration and storing the average in the avgArray list?

Here's an example:

var avgArray = [];
for(i=0; i < arr.length; i+=3) {
    total = arr[i] + (arr[i+1] || 0) + (arr[i+2] || 0);
    avg = total / 3;
    avgArray.push(Math.round(avg));
}

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

Sending an AJAX request to a Controller Action using an Object as input

I am currently using an AJAX call to a Controller within an ASP.NET MVC solution. The code snippet for the AJAX call is as follows: $.ajax({ url: "ControllerClass/ControllerMethod?date=" + date, type: "POST", dataType: 'json&a ...

Flask url_for usage done wrong

Running a flask server serves HTML pages with scripts stored in the static folder. An example script included in the header is: <script src="{{url_for('static', filename='js/viewer.js')}}"></script> The GET reques ...

JavaScript disrupting CSS animations

I've just embarked on creating a simple landing-page website. One component of the page is a basic image slider with navigation controls powered by JavaScript. I managed to get everything functioning except for achieving a smooth transition between im ...

Exclude the index element from the array

Could This Be Similar? Removing index key from Array to access object I'm looking to retrieve the value of term_id from an array without knowing the associated index number. Is there a way to do this? Currently, I have to access it using the ind ...

Retrieving data from multiple mongo collections and merging selected attributes from the output

I'm attempting to query a Mongo collection, extract an attribute from each object returned, use that attribute to retrieve data from another collection, and then combine the data. I am unsure of how to achieve this on mongoDB. To break it down, what I ...

Designing architecture for NPM packages in TypeScript

I am currently developing multiple NPM packages using TypeScript and I am exploring the most effective strategies for supporting various target architectures. When compiling to ES3, there is extensive support but it comes with additional boilerplate for c ...

Is JQueries Live functionality compatible with IE8?

Incorporating the JQuery fancy box, I have implemented a pop-up form with select fields that dynamically update a span element upon selection change. Although it works well thanks to fellow Stack Overflow users' help, it unfortunately does not functio ...

Use jQuery to select all div elements within another div and then verify each one's class

Currently, I am implementing a chat system where I display messages using jQuery, JSON, and PHP. The issue I am facing is that I need to iterate through each div within the "#chatMessages" container, which houses the messages, and verify its class existenc ...

What is the best way to display items using Typeahead.js in combination with the Bloodhound engine?

I am struggling to showcase a collection of items using typeahead with a JSON file as the data source. Unfortunately, none of my information is appearing on the screen. My objective is to list the names and utilize the other attributes for different purpo ...

Eliminate identical elements from an array

I am working with an associative array that looks like this: $arrz1=Array([sss] => Array ( [0] => 315 [1] => 330 [2] => 345 [3] => 315 [4] => 330 [5] => 345 [6] => 360 ...

Sending MVC3 model information as JSON to a JavaScript block

My challenge is to correctly pass my MVC3 model into a script block on the client side. This is the approach I'm taking in my Razor view: <script type="text/javascript"> var items = @( Json.Encode(Model) ); </script> The "Model" in t ...

there is no minimum height specified for the table

Hey there! I'm working on a dynamic table that I populate using data from my API. However, I'm facing an issue where I want the table to maintain a minimum height when there are only a few results, but I can't seem to make it work. I attemp ...

I'm experiencing some strange symbols on my page that look like ''. It appears to be a problem occurring between the servlet and the Javascript. How can I resolve this issue?

After retrieving a CSV file from my servlet, I noticed that characters like 'é', 'á' or 'õ' are not displaying properly on my page. Strangely, when I access the servlet directly via browser, everything appears fine. I atte ...

Experiencing inaccuracies in Magento's item validation process when checking the quantity of items being added to the cart

Upon entering a text string in the quantity field of the "Add to Cart" input box, Magento does not display an error message but instead considers it as a quantity of "1". Is there a way to modify this behavior and have the validation system mark strings ...

Encountering a connectivity issue with the MongoDB server

While I wrote my server IP on the mongoose connection string, I am unable to insert data into MongoDB. How can I resolve this issue? var express = require("express"); var app = express(); var mongoose = require('mongoose'); mongoose.connect(&ap ...

Submitting information via jQuery

https://i.stack.imgur.com/VU5LT.jpg Currently, I am working on integrating an event planner into my HTML form. However, I am facing difficulty in transferring the data ("meetup", "startEvent", "break") from HTML to my database. Using jQuery, I was able to ...

Coordinating Angular to communicate with Node.js to send and receive data

I am currently working on a project using express.js, but I would like to integrate angular into the project to create a single page application. The website currently refreshes the entire content from the server whenever a link is clicked, which seems ine ...

Issues arising when attempting to replicate a fetch object into an undefined object in React.js

I'm facing an issue where I have defined a 'poke' object and when I try to clone an object into it, I only get a promise fulfilled with the object's link , instead of the actual object. Here's the code snippet: let poke = fetch(url ...

What is the reason behind limiting the yawObject position to a maximum of 10 in the Three.js PointerLockControls source code?

Currently, I'm engrossed in developing a fundamental Demo FPS engine, employing the PointerLockControls example from the Three.js source located here: https://github.com/mrdoob/three.js/blob/master/examples/js/controls/PointerLockControls.js /** * @ ...

Issue with Java HtmlUnit - extracting null href value during website scraping

I'm currently working on a project that involves sending a URL to multiple websites for categorization and security risk scanning using Java and HtmlUnit. I have configured all the websites except www.virustotal.com, where I'm facing a challenge ...