Sum all numbers in array until a certain value is reached

I’m writing a function and this is the last piece of the puzzle, which I thought would be easy to deal with, but after some unsuccessful tinkering with for and while loops, I tried looking it up online and still couldn’t find an answer. I came across some obscure and complex solutions, but I think there should be a more straightforward way to solve this. For example, if I have an array

[1, 2, 3, 5, 7, 9]

And the argument is 10, the function should return 6 (1 + 2 + 3), because the sum of the values should be <= 10 (or whatever number is passed). If the argument is 4, the function should return 3 (1 + 2) and so on.

>Solution :

You can use a for loop:

const arg = 10
const arr = [1, 2, 3, 5, 7, 9]
let res = 0;
const calc = (arr, limit) => {
  for (num of arr) {
    if (num + res > limit) {
      break;
    }
    res += num;
  }
  return res;
}
console.log(calc(arr, arg))

Leave a Reply