Today we are here trying to go deep on another useful tool, the Javascript filter function. This function creates a new array made of elements that meet certain criteria starting from another array. Let’s analyze this function in detail:

The Basics

The basic syntax for using this method uses the following structure: 

The filter function basic syntax
The filter function basic syntax

from here we can identify the following parts: 

  • the elem variable refers to the current oldArray item we are testing against our condition.
  • the condition will determine what elems will end up or not inside newArray.

let’s try to make an example, say you wanted to use the javascript filter function to:

  • iterate through an array
  • find the elements of that array that are greater than or equal to 10
  • push those elements that satisfy this criteria into a new array

We can do that like this: 

filtering arrays
filtering arrays

Filtering Objects

A very useful case that often is necessary to work with for developers is to filter objects. This operation can be easily accomplished by the Javascript filter function, you will only need to be more specific in your condition and determine the key/keys to use as criteria for your new array: 

filtering objects
filtering objects

Conclusion

The javascript filter function can be useful in many cases and it can help you to create arrays suited for your needs. Hope this article was useful, remember to check out other resources to learn about this function on the official js docs. And don’t forget to check the javascript section of TheCoderSwag for keeping yourself always updated with the latest js methods and standards here

LEAVE A REPLY

Please enter your comment!
Please enter your name here