Remove the last element of an array while the sum of the array is bigger than a specific number

I’m trying to remove the last items of an array as long as the sum of the array is higher than a limit. The code I have works but seems to cause slow downs or crash. I was wondering if there’s a more elegant solution.

let array = [166, 157, 251, 171, 191];
let limit = 400;

for (
  let sum = array.reduce((a, b) => a + b); sum > limit; sum = array.reduce((a, b) => a + b)
) {
  array.pop();
}

console.log(array);

Answer

This solution will achieve the result in O(n)

You can achieve the result If you loop over the array and remember the last total i.e currentTotal and stop the iteration and break out from the loop if

currentTotal + val > limit

else add the current value in currentTotal and push that element in the result array.

let array = [166, 157, 251, 171, 191];
let limit = 400;

let currentTotal = 0;
const result = [];

for (let val of array) {
  if (currentTotal + val > limit) {
    break;
  }
  result.push(val);
  currentTotal += val;
}

console.log(result);