skip to Main Content

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

2

Answers


  1. 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:

    Login or Signup to reply.
  2. To solve this problem, you can use a regular expression to match elements that start with a number followed by any number of characters, and create a new array with those matched elements. Try to see if this code works for you.

    const arr = ['1a', 'a', '2b', 'b'];
    const regex = /^[0-9]+/; // regular expression to match numbers at start of string
    const result = arr.filter((item) => regex.test(item));
    
    console.log(result); // prints ['1a', '2b']
    console.log(result); // prints ['1a', '2b']
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search