Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Print elements of array with strings and number with each element

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']

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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,
  • i the i flag specifies a case-insensitive search.

References:

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading