summing up the initial elements from every array generated dynamically

My data is structured as follows:

{
    "questions": ["Variety of food options", "Food quality", "Freshness of food"],
    "countries": ["Netherlands", "Belgium", "France"],
    "values": [
        [
            [5, 88, 18],
            [50, 83, 10],
            [29, 78, 80]
        ],

        [
            [46, 51, 61],
            [95, 21, 15],
            [49, 86, 43]
        ],
        [
            [7, 46, 92],
            [54, 94, 31],
            [89, 96, 11]
        ]
    ]
}

I have a script for sorting the data like so;

 function calculateTotals() {
    var countryS = "France"
    var country = data.countries.indexOf(countryS);
    var values

  for (var question= 0; question < data.questions.length; question++) {
  // get the values for the question/country
  values = data.values[question][country];

  console.log(values)

Currently, the output in the console looks like this;

https://i.sstatic.net/Op0Tr.png

The script currently logs the values for each question indexed by country.

I want to sum up the elements in each array. For example, I would like to add the following numbers from the output;

29 + 49 + 89,

78 + 86 + 96,

80 + 43 + 11

I'm unsure of how to achieve this. I thought about using .pop()/.shift() or [0],[1],[2], but then I am not sure how to sum the numbers within the arrays?

If everything is clear, any guidance or assistance is greatly appreciated!

Plunk Here

Answer №1

One way to calculate totals is by using an array and iterating over the items.

This approach utilizes the Array#forEach method.

The forEach() method runs a provided function for each element in the array.

function calculateTotals() {
    var countryS = "France",
        country = data.countries.indexOf(countryS),
        sum = [];

    data.values.forEach(function (question) {
        question[country].forEach(function (a, i) {
            sum[i] = (sum[i] || 0) + a;
        });
    });
    console.log(sum);
}

var data = { "questions": ["Large choice of food", "Food quality", "Food freshness"], "countries": ["Netherlands", "Belgium", "France"], "values": [[[5, 88, 18], [50, 83, 10], [29, 78, 80]], [[46, 51, 61], [95, 21, 15], [49, 86, 43]], [[7, 46, 92], [54, 94, 31], [89, 96, 11]]] };

calculateTotals();

Answer №2

If you need to perform a specific operation on arrays, utilizing the map function can help you iterate through them efficiently.

Here's an example:

var arr = [[29,49,89], [78,86,96], [80,43,11]];

var final = arr.map(function(v){
  var res = 0;
  v.forEach(function(e){
     res += e;
  });
  return res;
});

console.log(final); //[167, 260, 134]

Alternatively, though not recommended for simplicity reasons, you could also accomplish the same task using:

var arr = [[29,49,89], [78,86,96], [80,43,11]];

var final = arr.map(function(v){
    return eval(v.join('+'));
});

console.log(final); //[167, 260, 134]

Answer №3

Check out the latest version of Plunkr

Here is the revised approach

function calculateTotals() 
{
  var countryS = "France"
  var country = data.countries.indexOf(countryS);
  var sum = [0, 0, 0];

  for (var question = 0; question < data.questions.length; question++) 
  {
    var values = data.values[question][country];
    for(var counter = 0; counter < values.length; counter++)
    {
      sum[counter] += values[counter];
    }
  }
  document.body.innerHTML += sum;
}

DEMO

var data = {
  "questions": ["Large choice of food", "Food quality", "Food freshness"],
  "countries": ["Netherlands", "Belgium", "France"],
  "values": [
    [
      [5, 88, 18],
      [50, 83, 10],
      [29, 78, 80]
    ],

    [
      [46, 51, 61],
      [95, 21, 15],
      [49, 86, 43]
    ],
    [
      [7, 46, 92],
      [54, 94, 31],
      [89, 96, 11]
    ]
  ]
}

function calculateTotals() {
  var countryS = "France"
  var country = data.countries.indexOf(countryS);
  var sum = [0, 0, 0];

  for (var question = 0; question < data.questions.length; question++) {
    var values = data.values[question][country];
    for (var counter = 0; counter < values.length; counter++) {
      sum[counter] += values[counter];
    }
  }
  document.body.innerHTML += sum;
}

calculateTotals();

Answer №4

To obtain the desired result, you can utilize array.reduce method.

for (var question= 0; question < data.questions.length; question++) {
      // Extract values for the organization/country
      values = data.values[question][country];

      console.log(values);

      var sumOfValues = values.reduce(
        function(previousVal, currentVal) { 
          return previousVal + currentVal; 
        }, 0);
      console.log("Sum of values");
      console.log(sumOfValues);
    }

Here is the link to Plunker where you can view the code: https://plnkr.co//TckVhx52VcMGgb0eZjzW?p=preview

UPDATE: array.reduce proves to be one of the most efficient methods available. More information on this topic can be found through various sources. Here's one resource I found helpful. How to find the sum of an array of numbers

Answer №5

Experiment with the following JavaScript code utilizing nested loops to calculate all possible additions:

var array = [[29,49,89], [78,86,96], [80,43,11]];
var resultArray;

for(var i = 0, length = array.length; i < length; i++) {
    for(var j = 0, length2 = array.length; j < length2; j++) {
        resultArray+= array[j][i]; 
    } 
}

If you prefer to compute one sum at a time:

    var finalResult;
    for(var i = 0, len = array.length; i < len; i++) {
        finalResult+= array[j]["YourIndex"]; 
    } 

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

At what point does the cleanup function in UseEffect activate the clearInterval() function?

In the process of creating a timer for a Tenzie game, there is an onClick function that changes the state of isTimerActive from false to true when a user clicks a button. The initial value of tenzie state is also set to false, but once the user completes t ...

Having trouble accessing the data I'm setting in a separate component using the Context API

Currently working on my own project and I've encountered a problem while using the Context API. It's my first time using it. The issue I'm facing is that I can't seem to console.log the data I'm setting. I'm trying to create ...

Javascript's associative arrays: a versatile tool for data organization

Is there a way to achieve the same functionality in JavaScript as this PHP code?: $this->gridColumnData[] = array('field' => 'id', 'width' => 50, 'title' => 'Enquiry Id') ; $this->gridColumn ...

Utilize the push method to form a new array

var teamMembers = [ ['John D. Adams', '1959-1967', 'Ohio'], ['Dawson Mathis', '1971-1981', 'Georgia'], ]; To generate this dynamically, I am implementing the code below: var data = ne ...

Adjust the properties within the component's styles using Angular 2

In this project, the objective is to dynamically change the background-color based on different routes. The goal is to display a specific color for UpcomingComponent while keeping the background-color consistent for all other routes. The approach involves ...

What is the best way to stream an app's data directly to a browser in real time?

My node application is currently able to read a stream from a Kafka producer and display it in real time using console.log. However, I would like to update my web application with the same real-time functionality. How can I achieve this? I typically start ...

Using a JavaScript variable in a script source is a common practice to dynamically reference

I have a scenario where an ajax call is made to retrieve json data, and I need to extract a value from the json to add into a script src tag. $.ajax({ url: "some url", success: function(data,response){ console.log("inside sucess"); ...

I am encountering errors when running NPM start

After setting up my webpack, I encountered an error in the terminal when attempting to run the code npm start. The specific error message was related to a module not being found. Can someone please assist me with resolving this issue? > <a href="/c ...

Using Promise to manipulate objects and arrays returned from functions

https://i.stack.imgur.com/jvFzC.png router.get('/', function (req, res, next) { var size = req.params.size ? parseInt(req.params.size) : 20; var page = req.params.page ? req.params.page>0 ? (size&(parseInt(req.params.page)-1)) : ...

Utilizing jQuery to execute functions from various files simultaneously with a single load statement

My goal is to achieve a basic include with jQuery, which involves loading functions from multiple files when the DOM is ready. However, this task proved to be more complex than anticipated: index.html <script type="text/javascript" src="res/scripts.js ...

Utilizing Material UI's TextField components for validating React forms

I've spent the past hour researching this topic and unfortunately, there isn't much information available on the internet. My goal is to validate input fields to ensure that all fields are filled out; otherwise, an error will be displayed. The le ...

Utilizing the Model URL Parameter in VueJS

In the context of , my objective is to dynamically modify a range input element and reflect that change in the URL. // Incorporating URL update with range input manipulation var Hello = Vue.component('Hello', { template: ` <div> &l ...

Tips for sharing a React component with CSS modules that is compatible with both ES Modules and CommonJs for CSS modules integration

Some frameworks, like Gatsby version 3 and above, import CSS modules as ES modules by default: import { class1, class2 } from 'styles.modules.css' // or import * as styles from 'styles.modules.css' However, other projects, such as Crea ...

Trigger an alert after a separate function is completed with jQuery

On my page, I have a function that changes the color of an element. I want to trigger an alert once this action is complete using changecolor(). However, I am unable to modify the changecolor() function due to certain restrictions. Is there a way to dete ...

Discovering the value of an item when the editItem function is triggered in jsGrid

Within my jsGrid setup, I have invoked the editItem function in this manner: editItem: function(item) { var $row = this.rowByItem(item); if ($row.length) { console.log('$row: '+JSON ...

How can I efficiently locate identical sequences of cells in two or more arrays?

Unique Example 1 We can explore an interesting scenario by considering two arrays: ('m','o','o','n','s','t','a','r','d') ('s','t','a', ...

What could be causing my Bootstrap carousel to only slide once?

I'm currently working on integrating a Bootstrap Carousel into my website, but I've encountered an issue where it moves only once and then becomes unresponsive. After checking the file order, I couldn't find any issues there. So, I'm qu ...

Retrieve the value of an object without relying on hardcoded index values in TypeScript

I am working with an object structure retrieved from an API response. I need to extract various attributes from the data, which is nested within another object. Can someone assist me in achieving this in a cleaner way without relying on hardcoded indices? ...

Incorporate information into a JSON structure within SAPUI5

While diving into SAPUI5, I decided to challenge myself by creating a basic form. Unfortunately, my attempts are falling short as the new entry I'm trying to add to my JSON model isn't showing up in the file when I run my code. No error messages ...

Using jQuery to create a flawless animation

I am currently working on an animation project, and I have shared my progress on jsfiddle. Below is the code snippet I have utilized: /* JavaScript: */ var app = function () { var self = this; var allBoxes = $('.box&apos ...