-1

The answer found here is so close to what i am looking for but not quite there. What I am looking is I have an array of integers, and a value that I need to subtract from across said array. i want to zero out each index before moving on to the next. I don't want any numbers less than 0 nor do i want any decimals.. so, for subtractFromSet([4, 5, 6, 7, 8], 25) instead of returning:

[0,0,0.666666666666667,1.666666666666666,2.666666666666666]

I want:

[0,0,0,0,5]
JDionne
  • 1
  • 1
  • Please re-write your question so it will be standalone one. Not one that depends on other Q. – Tal Rofe Jan 04 '21 at 21:18
  • Any special rules how to transform your input to the desired output? Because if you have an input `([a1, a2, ..., an], b)` your desired result seems to be `[0, 0, ... 0, sum(a1, .. an) -b)]` ie all elements of the array are `0` except the last, which is the difference between the sum of the array and `b` – derpirscher Jan 04 '21 at 21:26
  • Does my answer work for you? – Unmitigated Jan 08 '21 at 23:02

2 Answers2

0

You can loop until there is nothing left to subtract.

function subtractFromArr(arr, val){
  const res = [...arr];//copy
  for(let i = 0; i < res.length && val > 0; i++){
    const take = Math.min(res[i], val);
    res[i] -= take;
    val -= take;
  }
  return res;
}
console.log(subtractFromArr([4, 5, 6, 7, 8], 25));
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
-1

You can loop through the array "number" of times, while subtracting 1 from the current index and moving to the next index when index is equal to 0

function subtractFromSet(array, number) {
  var i = 0;
  do {
    array[i]--;
    number--;
    if(array[i] == 0) i++;
  } while (number != 0);
  return array;
}
subtractFromSet([4, 5, 6, 7, 8], 25);
Em1t
  • 1
  • 1