Another common looping scenario is to filter elements from a array. Usually it would be done like this:
As you may have guessed by the title of this story, JavaScript indeed have a method to handle this boilerplate.
Filter
Just like map
, Array#filter
will create a new array looping over a source array. The main difference is that it’ll only include a value in the new array if the callback returns true — that is, the callback tests if the element should be added. The callback signature is the same as map
’s:
- Current item value.
- Current item index.
- The array being looped on.
Your callback should return either a truthy or a falsy value. If you don’t return anything, undefined
is understood as false.
Review
- Use
filter
when you need to make a array with values that follow a criteria. - The filter callback return a truthy value to add the value to the new array or a falsy to ignore it.