Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
172 views
in Technique[技术] by (71.8m points)

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!

question from:https://stackoverflow.com/questions/65923927/how-to-set-up-consition-that-all-elements-of-one-arrays-must-be-equal-to-at-leas

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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`);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...