Home > Software design >  Sum all Elements in each Array on Multiple Dynamic Arrays
Sum all Elements in each Array on Multiple Dynamic Arrays

Time:01-12

How do we sum each array element in multiple arrays

ex : [[2, 1], [1, 4]]
output : [3], [5]

In this code is the sum based on the index in each array

const in_out = [
  [2, 1],
  [1, 4]
]

function calculate(arr) {
  a = arr.reduce((prev, curr) => prev   curr[idx = 0], 0)
  b = arr.reduce((prev, curr) => prev   curr[idx = 1], 0)
  c = [a   b]
  return c
}

console.log(calculate(in_out))

and what I want is summation based on each array, and dynamic "in_out" variable like this

[2, 1] = 3 and [1, 4] = 5

console.log(calculate (in_out [[2, 1], [1, 4]] ) );

and the output

[8]

CodePudding user response:

Use Array.reduce() method 2 times, the outer one will give you the transformed array and the nested one will give you the sum.

const list = [
  [2, 1],
  [1, 4]
];

function calculate(arr) {
  return arr.reduce((acc, items) => acc.concat(items.reduce((sum, curr) => sum   curr, 0)), [])
}

console.log(calculate(list))

CodePudding user response:

Just map and reduce:

const data = [[2, 1],[1, 4],[1,2,3,4],[],[9,8,7,6],[9]];

const result = data.map((arr) => arr.reduce((sum, num) => sum   num, 0));

console.log(result);
.as-console-wrapper{min-height: 100%!important; top: 0}

CodePudding user response:

Conventional way!

function calculate(arr){
  var arrSum = []; 

  for(let i = 0; i < arr.length; i  ) {
    for (let j = 0; j < arr[i].length-1; j  ) {
      arrSum[i] = (arr[i][j] arr[i][j 1]);
    }
  }

  return arrSum
}

Just copy it!

CodePudding user response:

You can try something like this

function in_out(arr){
  var output = []
  arr.map(arrElement=>{
     var sum = 0;
     arrElement.map(el=>{
        sum  = el
     })
     output.push([sum])
  })
  return output
}
console.log(in_out([[2,1],[1,4]]))

  •  Tags:  
  • Related