Home > Software design >  In a loop that results in several arrays, how to return an array with the sum of all of them
In a loop that results in several arrays, how to return an array with the sum of all of them

Time:12-12

I have an array of strings that, after a lot of effort, I have managed to turn into several arrays with a loop. So right now, the loop is giving me something like:

[4,5,6,7,8]
[4,5,6,7,8],[1,2,3,4,5]
[4,5,6,7,8],[1,2,3,4,5],[22,33,44,55,66]

If I place the return lower in the code, I get: [[4,5,6,7,8],[1,2,3,4,5],[22,33,44,55,66]]

What I need is the vertical sum of these arrays, so in this case it'd be: [27,40,53,66,80]

So far, I'm usign '.push'. Also, console.log gives me this answer but return results in 'undefined'. Any help with these two things would be welcome!

CodePudding user response:

Here's a simple readable version.

Create a new array and gradually fill it up

const verticalSummation = (nestedArray) => {
  if (nestedArray.length == 0) return [];
  const result = new Array(nestedArray[0].length).fill(0);
  for (let i = 0; i < result.length; i  ) {
    for (const arr of nestedArray) {
      result[i]  = arr[i];
    }
  }
  
  return result;
}
    
console.log(verticalSummation([[4,5,6,7,8],[1,2,3,4,5],[22,33,44,55,66]]));

CodePudding user response:

1) You can easily achieve the result using map and reduce

const arr = [
  [4, 5, 6, 7, 8],
  [1, 2, 3, 4, 5],
  [22, 33, 44, 55, 66],
];

const result = arr[0].map((_, i) => arr.reduce((acc, curr) => acc   curr[i], 0));
console.log(result)

2) Using simple for loops

const arr = [
  [4, 5, 6, 7, 8],
  [1, 2, 3, 4, 5],
  [22, 33, 44, 55, 66],
];

const result = [];

for (let i = 0; i < arr[0].length;   i) {
  let sum = 0;
  for (let j = 0; j < arr.length;   j) {
    sum  = arr[j][i];
  }
  result.push(sum);
}

console.log(result);

CodePudding user response:

let arrays = [
  [4,5,6,7,8],
  [1,2,3,4,5],
  [22,33,44,55,66],
];
let ar_sum = [];

for (let x = 0; x < 5; x  ) {
    let sum = 0;
    arrays.forEach((array) => {
        sum  = array[x];
    });
    ar_sum.push(sum);
}
console.log(ar_sum);

  • Related