Search code examples
javascriptarraysrefactoringstartswith

Filter array of strings, keeping only ones starting with vowels


I realise I've massively overengineered this, but as I'm just starting out with JS, I can't think of how to condense this into something not entirely ridiculous. I know I'm probably going to kick myself here, but can someone refactor this for me?

The aim was to create a new array from a provided one, one that only contained strings starting with vowels. It also needed to be case insensitive.

let results = []

for (let i = 0; i < strings.length; i++) {
  if ((strings[i].startsWith('a')) || (strings[i].startsWith('A')) || (strings[i].startsWith('e')) || (strings[i].startsWith('E')) || (strings[i].startsWith('i')) || (strings[i].startsWith('I')) || (strings[i].startsWith('o')) || (strings[i].startsWith('O')) || (strings[i].startsWith('u')) || (strings[i].startsWith('U'))) {
    results.push(strings[i])
  }
}

return results

Solution

  • You can use a single RegExp and Array.prototype.filter() for that:

    console.log([
      'Foo',
      'Bar',
      'Abc',
      'Lorem',
      'Ipsum'
    ].filter(str => /^[aeiou]/i.test(str)));

    Array.prototype.filter() returns a new array with all the elements that pass (return a truthy value) the predicate.

    RegExp.prototype.test() returns true if the RegExp finds a match on the string you pass in.

    Then, /^[aeiou]/i means:

    • ^ matches the start of the string.
    • [aeiou] matches any of the characters inside the square brackets, a single time.
    • i is a case-insensitive modifier.