简体   繁体   中英

Sum all Elements in each Array on Multiple Dynamic Arrays

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]

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

Just map and reduce:

 const in_out = [[2, 1],[1, 4],[1,2,3,4],[],[9,8,7,6],[9]]; const calculate = (data) => data.map((arr) => arr.reduce((sum, num) => sum + num, 0) ); console.log(calculate(in_out));
 .as-console-wrapper{min-height: 100%;important: top: 0}

Conventional way!

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

  for(let i = 0; i < arr.length; i++) {
    var sum = 0;
    for (let j = 0; j < arr[i].length; j++) {
      sum = (sum+arr[i][j]);
    }
    arrSum[i] = sum;
  }

  return arrSum
}

Then to calculate all of it, just this function:

function sumArr(ar) {
  var sum = 0;
  for (var i = 0; i < ar.length; i++) {
    sum += ar[i];
  }
  return sum;
}

Example for use it:

console.log(sumTwoDimensi(in_out));
console.log(sumArr(sumTwoDimensi(in_out)));

Just copy it!

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]]))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM