Looping through an array of items and computing the mean value

Given the current data structure, my goal is to calculate the average value for each column across all items in the contenders object. The next step is to convert this information into an array of arrays. Each subarray should consist of two values: the rounded average of the column and an incremental value starting from 0.

output = [[6, 0], [4, 1], [3, 2], [3, 3], [6, 4]]; 

Here's an illustration of the input structure:

input = {
  categories: [
    "Cat 1",
    "Cat 2",
    "Cat 3",
    "Cat 4",
    "Cat 5"
  ],
  contenders: {
    item1:       [5, 3, 4, 4, 6],
    item2:       [6, 10, 4, 4, 6],
    item3:       [6, 3, 4, 9, 6],
    item4:       [8, 3, 5, 4, 6],
    item5:       [9, 3, 4, 4, 6],
    item6:       [10, 2, 7, 4, 6],
    item7:       [4, 3, 4, 4, 6],
    item8:       [1, 5, 4, 4, 6]
  },
  misc: [0, 3, 4, 4, 6]
};

I have a function that can handle calculating averages:

function getAvg(data) {
    return data.reduce(function (p, c) {
                return p + c;
            }) / data.length;
} 

However, I'm struggling with iterating through the item values to achieve the desired outcome.

Answer №1

If my understanding is correct and you are looking to calculate an average for each column, where each first element in all arrays within your items keys serves as an example, then the best approach would be to create an array for each column and utilize the average function. However, there is a way to calculate the average without explicitly creating these arrays:

var input = { categories: ["Cat 1", "Cat 2", "Cat 3", "Cat 4", "Cat 5"], contenders: { item1: [5, 3, 4, 4, 6], item2: [6, 10, 4, 4, 6], item3: [6, 3, 4, 9, 6], item4: [8, 3, 5, 4, 6], item5: [9, 3, 4, 4, 6], item6: [10, 2, 7, 4, 6], item7: [4, 3, 4, 4, 6], item8: [1, 5, 4, 4, 6] }, misc: [0, 3, 4, 4, 6] }

var output = []

var cols = input.contenders.item1.length

for(var i=0; i<cols; i++){
  output[i] = [0,i]
}

for(var key in input.contenders){
  var arr = input.contenders[key]
  for(var k = 0; k<cols; k++){
    output[k][0]+=arr[k] 
  }
}

for(var i=0; i<cols; i++){
  output[i][0] = Math.round(output[i][0]/Object.keys(input.contenders).length) 
}

console.log(output)

Answer №2

To extract each item from the contenders object and generate a new array, you can utilize both Object.keys and map:

function calculateAverage(data) {
  return data.reduce(function (prev, curr) {
    return prev + curr;
  }) / data.length;
} 
var inputData = {
  categories: [
    "Cat 1",
    "Cat 2",
    "Cat 3",
    "Cat 4",
    "Cat 5"
  ],
  contenders: {
    item1:       [5, 3, 4, 4, 6],
    item2:       [6, 10, 4, 4, 6],
    item3:       [6, 3, 4, 9, 6],
    item4:       [8, 3, 5, 4, 6],
    item5:       [9, 3, 4, 4, 6],
    item6:       [10, 2, 7, 4, 6],
    item7:       [4, 3, 4, 4, 6],
    item8:       [1, 5, 4, 4, 6]
  },
  misc: [0, 3, 4, 4, 6]
};
console.log(Object.keys(inputData.contenders).map(function(key, index) {
  return [calculateAverage(inputData.contenders[key]), index];
}));

Answer №3

To retrieve the properties, you can utilize Object.keys, and then loop through the values using Array.prototype.forEach.

var data = { teams: ["Team A", "Team B", "Team C"], players: { player1: [6, 8, 7], player2: [9, 4, 7], player3: [5, 6, 7] }, scores: [10, 8, 7] },
    result = [],
    total = [], quantity = [];

Object.keys(data.players).forEach(function (key) {
    data.players[key].forEach(function (value, index) {
        total[index] = (total[index] || 0) + value; 
        quantity[index] = (quantity[index] || 0) + 1;
    });
});
result = total.map(function (value, index) {
    return [Math.round(total[index] / quantity[index]), index]
});

document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');

Answer №4

It is highly recommended to make use of Object.keys as advised in previous responses. Nevertheless, if for some reason compatibility becomes an issue, you do have the option of creating a string reference to access the desired arrays:

for (var x=1; x<9; x++) { performAction(input.contenders["item"+x]); }

This approach assumes that you already know both the quantity and names of the items beforehand.

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

Is there a way to inherit styles from a parent component and apply them to a child component in the following form: `<Child style={{'border': '1px solid red'}}` ?

I am having an issue where the child component, ComponentA, is not inheriting the style I have defined in the parent component. <ComponentA style="{'border':'1px solid red'}" /> Any suggestions on how to resolve this? & ...

A guide on using Jest.js to test labels within Vue 3 Quasar components by utilizing a forEach loop

Within my Vue Quasar component, a badge is implemented as shown below: <q-badge :color="green" text-color="white" :label="`${value.toFixed(2)}%`" /> The corresponding script is structured like this: <scri ...

Is there a way to prevent the onClick event from executing for a particular element in React?

Currently working with Material UI, I have a TableRow element with an onClick event. However, I now need to incorporate a checkbox within the table. The checkbox is enclosed in a TableCell element, which is nested within the TableRow. The issue arises wh ...

Comparing Embedded and Linked JS/CSS

In my experience, I understand the advantages of using linked CSS over embedded and inline styles for better maintainability and modularity. However, I have come across information suggesting that in certain mobile web development applications, it may be m ...

Utilizing AJAX with FullCalendar to seamlessly insert Bootstrap modal inputs into an SQL table

I've been struggling to implement user input from a modal into my phpMyAdmin database. Any assistance would be highly appreciated. 1) Triggering a modal with the select callback: select: function(start, end, allDay) { $('#myModal') ...

What is the best way to retrieve the result of a JavaScript function in an HTML form?

I'm currently developing a JavaScript app that involves selecting a random question from an array and combining it with a random object from another array. Here's a glimpse of how my app is structured: Array.prototype.random = function (length) ...

What is the best way to manage external redirects for a React app on the client side?

I am creating a web application that utilizes the True Layer open banking API. The frontend is built using React with react router, and the backend is created with Express and Node.js. Currently, I am serving the static files using the react build script: ...

Doing an asynchronous function in the route.js file in Node.js

I'm facing an issue with my application that uses nodejs as the backend and has some Python scripts integrated. The problem lies in making the 'PythonShell' function asynchronous, but for some reason, it's not working as expected. In o ...

What steps can be taken to enable users to draw a path on a Google Map?

I'm working on a new project for a Facebook app that will allow users to map out their marathon route using Google Maps. I plan to utilize mySQL database records to store fixed points along the path (such as specific locations based on latitude and lo ...

Utilizing Vue.js to set the instance global property as the default value for a component prop

Is it possible to access a global property from my vue instance when setting a default prop value in my component? This is what I would like to achieve props: { id: { type: String, default: this.$utils.uuid } } I attempted to use an arrow fun ...

Explanation of the role of `::` in Angular Formly

My goal is to master working with Angular, but I'm struggling to grasp some of the syntax used in the guides and examples on the official website. In one example for defining a button form control, I came across this template: <div><button t ...

Hide HTML div on click

Why does the button disappear when I click on it, but the status refreshes? Javascript $( ".refreshstatus" ).click(function(){ $( ".navplayers" ).load('stats.php'); }); CSS .refreshstatus{ font-family:'Noto Sans'; font-w ...

Issues with displaying ngAnimate animations

For the past 10 hours, I've been attempting to get my animations to function properly. It seems that they only work when I include the animate.css stylesheet and use the "animated classname". However, when I try to create custom entrance and exit anim ...

An easy guide to comparing date and time using Moment.js

Hey there, I'm looking for some help in validating two instances of date time moments. I am using this helpful Package which allows us to select hour, minute, and second. I want to validate whether the selected date time is before or after, as shown i ...

How can I showcase the index of `<tr>` and `<td>` elements in a dynamically generated table

How can I print the index of table rows and data on click in javascript? <html> <head> <title>Table Creation</title> <script language="javascript" type="text/javascript"> function createTable() { ...

I'm unsure of my recollection on how to utilize the /* syntax in JavaScript

Hey there, I'm facing a little issue. Can someone remind me how to correctly use the /* in JavaScript when dealing with URLs? For instance: if(URL == "www.thing.com/"){} I can't quite remember where to insert the /* so that it applies not just ...

What is a reliable method for consistently updating backend C# with user-side JS data whenever it is altered?

I'm working on a front end JS application that includes visual sliders. I need to send the updated slider information to the C# backend (ASP.NET) whenever a user makes changes. After some research, it seems like AJAX is the most efficient way to achie ...

The Aframe 'initiatingEvents' feature does not seem to be functioning properly when using a gltf model

I'm attempting to add animation to the movement of a gltf model in A-Frame by clicking on a button. The animation functions properly when the 'startEvents' property is not included, but fails to work once the property is added. Interestingly ...

Transferring an object from Javascript to C++/CX following a C++/CX interface in Windows Runtime Components

As a newcomer to Windows Runtime Component, I've been exploring ways to accomplish the following task. I'm looking to extend a C++ interface in JavaScript. namespace MySDK { public interface class LoggerPlugin { public: virt ...

How to Filter, Sort, and Display Distinct Records in an HTML Table with jQuery, JavaScript, and

In the HTML page, there will be a total of 6 tabs labeled A, B, C, D, E, and F along with 2 dropdowns. The expected behavior is as follows: The user will choose a value from the 2 dropdown menus. Based on the selected value, filtering should be applied to ...