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

how to restart a for in loop iteration in javascript

I need to restart the loop every time the if statement occurs so that the correct roman numeral conversion works

by pushing the key(roman numeral) of the iterator to counter,
and by subtracting the value of the iterator from the input num then I want the loop to start again from the beginning


let conversionChart = {
  m:1000,
  cm:900,
  d:500,
  cd:400,
  c:100,
  xc:90,
  l:50,
  xl:40,
  x:10,
  ix:9,
  v:5,
  iv:4,
  i:1
}

let newArr = [];
let counter = [];

for(let i in conversionChart){
  if(num >= conversionChart[i]){
    counter.push(i)
    num = num - conversionChart[i]
    continue;
    }
   }




 return counter
}

console.log(convertToRoman(36));``` 

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

>Solution :

You’d need to wrap that loop in another loop that continues for as long as there is something to convert:

let conversionChart = {
  m: 1000,
  cm: 900,
  d: 500,
  cd: 400,
  c: 100,
  xc: 90,
  l: 50,
  xl: 40,
  x: 10,
  ix: 9,
  v: 5,
  iv: 4,
  i: 1,
};

function convertToRoman(num) {
  const counter = [];
  // while there is still something to convert...
  while (num > 0) {
    for (let romanNumeral in conversionChart) {
      if (num >= conversionChart[romanNumeral]) {
        counter.push(romanNumeral);
        num = num - conversionChart[romanNumeral];
        break;  // ... out of the inner "romanNumeral ..." loop
      }
    }
  }
  return counter.join("");
}

console.log(convertToRoman(36));
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