Lambda JS #3: Filter

Lubien
Lambda JS
Published in
2 min readMay 27, 2019

[Table of Contents] [Previous] [Next]

Another common looping scenario is to filter elements from a array. Usually it would be done like this:

Yea, once again you write that boilerplate for loop.

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:

  1. Current item value.
  2. Current item index.
  3. 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

  1. Use filter when you need to make a array with values that follow a criteria.
  2. The filter callback return a truthy value to add the value to the new array or a falsy to ignore it.

Links

--

--

Lubien
Lambda JS

Web developer that loves to make JoJo references