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

523
Visualizações
How to sum numbers in array by index in javascript

I have an array

const array = [6,2,6,7,5,9];

I want sum of all numbers till 7 in array

I tried .reduce but it gave me sum of whole array, How can I do that so?

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

0

You're going to have to jump through a lot of hoops with reduce. You'd need to find the index of 7, then splice up to that index, and then reduce over the spliced array. Muy complicado!

It's much simpler to create a sum variable, and loop over the array. Add each number to the sum, and when the number is 7 break the loop.

It's worth noting this strategy wouldn't work for duplicate numbers like 6 for example because which 6 would you choose?

const arr = [6, 2, 6, 7, 5, 9];

let sum = 0;

for (const n of arr) {
  sum += n;
  if (n === 7) break;
}

console.log(sum);

about 4 years ago · Juan Pablo Isaza Relatório

0

This is doable with just a for loop:

const array = [6, 2, 6, 7, 5, 9];
let sum = 0;

for (let i = 0; i < array.length; i++) {
  sum += array[i];
  if (array[i] == 7) break;
}

// outputs the sum of [6,2,6,7], which is 21
console.log(sum);

Here we take the sum of numbers till 7 to mean the sum of all numbers in our array up until the first instance of 7.

about 4 years ago · Juan Pablo Isaza Relatório

0

Here you go,

const array = [6, 2, 6, 7, 5, 9];
const found = array.find(element => element >= 7);
const newArr = array.indexOf(found);
const arr1 = array.slice(0,(newArr + 1));
const sum = 0;
const result = arr1.reduce(
  (previousValue, currentValue) => previousValue + currentValue,
  sum
);

console.log(result); //output 21
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