Array contains number of elements. I need to print elements of array with strings and number with each element.
For example
Input
['1a', 'a', '2b', 'b']
Output should be
New array ['1a', '2b']
>Solution :
The easiest answer is, I think:
// the initial Array:
let input = ['1a', 'a', '2b', 'b'],
// using Array.prototype.filter() to filter that initial Array,
// retaining only those for whom the Arrow function returns
// true (or truthy) values:
result = input.filter(
// the Arrow function passes a reference to the current
// Array-element to the function body; in which we
// use RegExp.test() to check if the current Array-element
// ('entry') is matched by the regular expression:
// /.../ : regular expression literal,
// \d: matches a single number in base-10 (0-9),
// [a-zA-Z]: matches a single character in the range
// of a-z or A-Z (so lowercase or uppercase):
(entry) => (/\d[a-zA-Z]/).test(entry));
console.log(result);
There are refinements, of course, such as:
`/^\d{1,2}[a-z]+$/i`,
/.../regular expression literal,^: the sequence starts at the beginning of the string,\d{1,2}: a base-10 number character, which occurs a minimum of 1 time, and a maximum of 2 times (obviously the numbers can be amended to suit your specific needs),[a-z]+: a character in the range of (lowercase) a-z, that occurs one or more times,$: the end of the string,itheiflag specifies a case-insensitive search.
References:
-
Bibliography:
-
"Regular expressions." (A guide, MDN).