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