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

167
Vistas
SUM certain column in an array (Javscript)

I have very simple question, i am learning javascript.

I have this 2D array :-

let text = [[1,a],[2,b]]

And I want to sum the numeric values of array, I know how to do it using for loop but is there any way to do in shorter way like we can do it using 1D array by using reduce?

If i have this array :-

let text = [1,2]

I can easily sum it in one line like this :-

text.reduce((a,b) =>  a + b)

Is there any way to do same way with 2d array too which also has string values.

Thanks

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

You may use that same Array.prototype.reduce() slightly modified to build up a custom summarizing function that may accept source array and col variable indicating target column:

const src = [[1,'a'],[2,'b']]

const sumByCol = (arr, col) => 
  arr.reduce((acc, row) => acc + row[col], 0)
  
console.log(sumByCol(src,0))

about 4 years ago · Juan Pablo Isaza Denunciar

0

You could do the following

let text = [[1,'a'],[2,'b']]
let numbers_only = text.flat().filter(x => Number(x))
let sum = numbers_only.reduce((a,b) => a + b)

//answer = 3

As a one-liner -

   let sum = text.flat().filter(x => Number(x)).reduce((a,b) => a + b)
about 4 years ago · Juan Pablo Isaza Denunciar

0

You can achieve it in a single line by doing this :

let text = [[1,'a'],[2,'b']]

console.log(
  text.flat()
  .filter((item) => typeof item === 'number')
  .reduce((total, item) => total + item)
)

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