alexc
alexc

Reputation: 1310

adding the first item from each dynamically created array together

Below is the structure of my 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]
        ]
    ]
}

Here is my script for sorting it;

 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, this outputs this to the console;

enter image description here

So, currently this script is logging the values for each question indexed by country.

I would like to add together each item in this array. So, from this output I would like to do the following additions;

29 + 49 + 89,

78 + 86 + 96,

80 + 43 + 11

I'm not sure how I can do this?

I thought that perhaps using .pop()/.shift() 3 times might work, or just using [0],[1],[2]. However, after returning a single item in the array, I'm not sure how to add the 3 arrays numbers together?

Hope everything is clear, any help/advice is much appreciate!

Plunk Here

Upvotes: 3

Views: 115

Answers (5)

user3378165
user3378165

Reputation: 6896

Try the following with pure JavaScript with nested loops:: (If you want to get all the additions)

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

for(var i = 0, len = arr.length; i < len; i++) {
    for(var j = 0, len2 = arr.length; j < len2; j++) {
        resultArr+= arr[j][i]; 
    } 
}

If you only want to get one sum at a time:

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

Upvotes: 0

Muhammad Ahsan Ayaz
Muhammad Ahsan Ayaz

Reputation: 1947

You can use array.reduce to achieve the desired output.

for (var question= 0; question < data.questions.length; question++) {
      // get the 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's the plunkr https://plnkr.co//TckVhx52VcMGgb0eZjzW?p=preview

EDIT: array.reduce is one of the fastest methods available. Many links can be found for the info. I've got one here. See the answers. How to find the sum of an array of numbers

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386644

You could use an array for the sum amd iterate over the items as well.

Basically this proposal uses Array#forEach.

The forEach() method executes a provided function once per array element.

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();

Upvotes: 2

gurvinder372
gurvinder372

Reputation: 68393

try the updated plunkr

Here is the updated method

  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();

Upvotes: 0

choz
choz

Reputation: 17868

You can use array map function to iterate over them and perform such an operation.

E.g.

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]

For simpler, but not recommended, you can also achieve it by doing,

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]

Upvotes: 0

Related Questions