How to set up consition that all elements of one arrays must be equal to at least one element of the another array in JavaScript?

Transforming roman numerals into numbers! A user enter his one roman number, and the code transfers his/her roman number into classic number.

var roman = prompt("Enter roman number", roman);
var romandigits = roman.toString().split(""); // spliting roman number entered into an array!
let romannumerals = ["M", "D", "C", "L", "X", "V", "I"];

Now condition that suppose to be set is: ALL elements of the array romandigits have to be equal to AT LEAST one element of the array romannumerals!

Answer

You can create a set of romannumerals

let numeralSet = new Set(romannumerals);

Then you can check that each digit is in that set

let badDigits = romanDigits.filter((c) => !numeralSet.has(c))

and then check whether there are any badDigits:

if (badDigits.length) {
    console.error(`Invalid roman number ${roman} contains non-digits ${badDigits}`);
}

So putting it all together

let roman = prompt("Enter roman number");
let romandigits = [...roman];
let romannumerals = ["M", "D", "C", "L", "X", "V", "I"];
let numeralSet = new Set(romannumerals);
let badDigits = romandigits.filter((c) => !numeralSet.has(c))
if (badDigits.length) {
    console.error(`Invalid roman number ${roman} contains non-digits ${badDigits}`);
} else {
    console.log(`${roman} is OK`);
}

Leave a Reply

Your email address will not be published. Required fields are marked *