Code Lab

Words that contain a part

MediumStrings10 min

Write a function filterWords(words, part) that returns the words from the array words that contain part as a substring. For ['ant', 'tiger', 'elephant'] and 'ant' the answer is ['ant', 'elephant'].

  • words is an array of words (it can be empty). part is a non-empty string of letters.
  • The search is case insensitive: with 'ant' the words 'Antelope' and 'PLANT' match too, and 'ANT' as part finds 'plant'.
  • part can be anywhere in the word: at the start, in the middle or at the end.
  • Keep the words in their order and with their own spelling. If a word is in the list twice, it is in the answer twice.
  • If nothing matches, return an empty array.
  • Return a new array. Do not change words.

includes and filter do most of the work.

Examples

filterWords(['ant', 'tiger', 'elephant'], 'ant')

Returns [ 'ant', 'elephant' ]

filterWords(['Antelope', 'cat', 'PLANT'], 'ant')

Returns [ 'Antelope', 'PLANT' ]

filterWords(['dog', 'cat'], 'ant')

Returns []

Asked at Nvidia · Source

Loading the editor...
  1. InputfilterWords([ 'ant', 'tiger', 'elephant', 'pants' ], 'ant')
    Expected[ 'ant', 'elephant', 'pants' ]
  2. InputfilterWords([ 'dog', 'cat' ], 'ant')
    Expected[]

Hidden tests run on Submit.