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

105
Visualizações
JS Reduce: sum specific position in a nested array of numbers

I want to reduce only a specific position in a nested number array

const array1 = [[1,2,3],[4,5,6],[7,8,9],[11,12,13]];

console.log(array1.reduce((prev, curr) => prev[2] + curr[2]));

The result is NaN, another solution?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

1) You should use prev not prev[2] as

prev is of type number that you are returning not an array

2) If you are adding the number then it is better to take initial value as 0 as a second argument to the reduce method.

If you won't pass second argument, then reduce will take the array element at 0 index as the starting value i.e [1, 2, 3] and then if you add [1, 2, 3] + curr[2] then it will produce value as 1,2,36, which you are not expecting

const array1 = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9],
  [11, 12, 13],
];

console.log(array1.reduce((prev, curr) => prev + curr[2], 0));

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