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? Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of 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? without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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`);
}
We are here to answer your question about 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? - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji