Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JavaScript Loop to decrement element in last index of Array

Array = [ 1, 3, 7, 2 ]

1st Iteration = [ 1, 3, 7, 1 ]
2nd Iteration = [ 1, 3, 7, 0 ]
3rd Iteration = [ 1, 3, 6 ]
4th Iteration = [ 1, 3, 5 ]

So on & so forth…

Final Iteration should be an empty []

I’m wanting to create a loop that takes the last index & decrements the value by 1 on each iteration. When the value in the last index = 0 it should pop it…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Any help would be appreciated.

>Solution :

We can use while and Array.prototype.pop().

function solution(array) {
  while (array.length !== 0) {
    while (array[array.length - 1] >= 1) {
      array[array.length - 1] -= 1;
      console.log(array);
    }
    array.pop();
    console.log(array);
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading