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

92
Views
At what index does the sum reach a certain value

I have an array of numbers and some limit.

const a = [1,2,1,3,4,1,2];
const limit = 5;

What's the most javascripty way of reducing this array to the index such that the sum from the beginning to the index would exceed the limit?

I've done

function findIndex(nums, limit) {
      let s = 0;
      for (let [index, num] of nums.entries()) {
        s += num;
        if (s >= limit) {
          return index;
        }
      }
      return nums.length;
    }
findIndex([1,2,1,3,4,1,2], 5)
3

Is there a more neat way of doing this using reduce or something else?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

As you're after the index, you could look at using the array method .findIndex(). The below code adds to sum for each item in arr, and then checks whether the new accumulated sum value is greater than or equal to the limit. If it is, the callback for findIndex will return true, giving you the index of the item it returned true for. If the callback function to findIndex doesn't return true for any values, it will result in -1, which you can then check before you return to see if you need to return the array length or the found index:

const findIndex = (arr, limit) => {
  let sum = 0;
  const idx = arr.findIndex((num, idx) => (sum+=num) >= limit);
  return idx > 0 ? idx : arr.length; 
}

console.log(findIndex([1,2,1,3,4,1,2], 5));

about 4 years ago · Juan Pablo Isaza Report

0

Since you need the

1) index upto which the sum is greater or equal to limit

2) You want to return early as soon as the sum exceeds limit

then you should go for old school for loop. There is no need to accumulate the index and value using nums.entries()

function findIndex(nums, limit) {
  let sum = 0;
  for (let i = 0; i < nums.length; ++i) {
    sum += nums[i];
    if (sum >= limit) return i;
  }
  // Return something explicitely to 
  // indicate that sum can't exceeds limit.
  // You may return -1 if you like
}
console.log(findIndex([1, 2, 1, 3, 4, 1, 2], 5));

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!