Cumulative total with restart upon reaching a limit with a condition

Viewed 45

I have an array:

arr = [2, 4, 3, 7, 8, 2, 3, 4, 9, 1];

All the numbers are below '10'. I want the cumulative total of the numbers. But with two conditions:

  1. upon reaching a total closest to '10' the last number that makes total to be less than or equal to '10' should be replaced with '10' AND
  2. the cumulative total starts from next number.

So, the output should be:

outputArr = [2, 6, 10, 10, 8, 10, 3, 10, 9, 10];

I have this code:

arr = [2, 4, 3, 7, 8, 2, 3, 4, 9, 1];
total = 0;
outputArr = [];
for (i = 0; i < arr.length; i++) {
  if (total + arr[i] <= 10) {
    total += arr[i];
    outputArr.push(total);
  } else {
    total = arr[i];
    outputArr.push(total);
  }
}
console.log(outputArr);

This code gives me this output:

outputArr = [2, 6, 9, 7, 8, 10, 3, 7, 9, 10]

Here, cumulative total and its restarting upon reaching 10 works fine. But the problem as you see is: before restarting, it can't replace last item with 10.

Any help is much appreciated.

1 Answers

You could update the output array based on whether the cumulative sum is < 10 or == 10 or > 10

let input = [2, 4, 3, 7, 8, 2, 3, 4, 9, 1],
    output = [],
    cumulative = 0;

for (let i = 0; i < input.length; i++) {
  cumulative += input[i];

  if (cumulative < 10) {
    output.push(cumulative)
  } else if (cumulative == 10) {
    output.push(10)
    cumulative = 0
  } else {
    output[i-1] = 10
    cumulative = input[i]
    output.push(cumulative)
  }
}

console.log(output)

Related