Is there a way to complete this challenge more efficiently?

Tell us what’s happening:
I just completed the second javaScript project and was wondering if there is a way to complet this challenge without hardcoding the letters in the “COMBINATIONS” array and repeating the if and else if statements ?

  **Your code so far**

function convertToRoman(num) {
let combinations = [["", "M", "MM", "MMM", "MMMM", "MMMMM", "MMMMMM", "MMMMMMM", "MMMMMMMM", "MMMMMMMMM"], ["", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"], ["", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"], ["", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"]];
let number = num.toString();
let numLen = number.length;
let roman = [];

for (let i = 0; i < numLen; i++) {
  if (numLen === 4) {
  } else if (numLen === 3) {
    roman.push(combinations[i + 1][number[i]])
  } else if (numLen === 2) {
    roman.push(combinations[i + 2][number[i]])
  } else if (numLen === 1) {
    roman.push(combinations[i + 3][number[i]])
return roman.join("");
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.93 Safari/537.36

Challenge: Roman Numeral Converter

Link to the challenge:

I think the combinations array has to stay, I can see no way around without then having to then create more if/else/switch statements instead

for the logic behind applying to the combinations array to the right numbers though, I found this solution on stack overflow that you might like!

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.