Y
Y
Yuri Tolstykh2021-02-10 05:56:32
JavaScript
Yuri Tolstykh, 2021-02-10 05:56:32

How to check the elements of an array for the presence of certain elements?

How to check array elements for content

Array: arr ['3' , '*' , 'IV']
Array consists of strings.

arr[0] and arr[2] - can only contain Arabic (1,2,3,4,5…) or Roman numerals (I,II,III,IV,V…)
arr[1] can only contain operators - * , / , + , -

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
dollar, 2021-02-10
@dollar

With regular expressions :

arr = ['3' , '*' , 'IV'];
let r_num = /^(?:\d+|[IVXLC]+)$/;    //либо арабское, либо римское число
let r_sig = /^[*\/]$/;               //знак умножения или деления

if (arr[0].match(r_num) && arr[1].match(r_sig) && arr[2].match(r_num)) {
  console.log("Условие выполнено!");
} else {
  console.log("Ошибка!");
}

A
Alexander, 2021-02-10
@Seasle

/\d+/.test(arr[0]);
/[\-\+\*\/]/.test(arr[1]);
/[IVXLCDM]+/.test(arr[2]);

S
Sergey Sokolov, 2021-02-10
@sergiks

It is better to check the number in Arabic numerals through the Number(num_string)
Number in Roman numerals with a ready-made library, for example, sguest / RomanJS - because just having the right characters is not enough. Roman numbers can be written in different ways:

  • capital IX
  • small ix
  • special Unicode characters: Ⅸ (that's one character)
The correct letters can write the wrong number "IMIVIIIIIII"
Operation signs are the easiest, a regular expression is suitable there/^[\*\/\+-]$/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question