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

Viewed 123

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);

4 Answers

You don't need to sum the entire array each time through the loop. Calculate the sum once at the beginning. Then subtract the element that you removed from the sum.

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

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

console.log(array);

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);

To improve efficiency, as Barmar stated, you can calculate the sum once and update it in each loop iteration. I believe a while loop expresses this idea the most clearly:

const arr = [166, 157, 251, 171, 191];
const limit = 400;

let sum = arr.reduce((a, b) => a + b)
while (sum > limit) {
  const lastNum = arr.pop();
  sum -= lastNum;
}

console.log(arr)

This should work:

const threshold = 10;
let sum = 0;
arr = [1, 2, 3, 5, 6, 3];
const filteredArray = arr.filter((el) => {
  sum += el;
  return sum <= threshold;
});

Related