Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

224
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda