Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

166
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda