Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

520
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!