Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

222
Views
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]
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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}

about 4 years ago · Juan Pablo Isaza Report

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!

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!