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: 

var newArray = oldArray.filter(function(elem) {
  return condition;

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: 

let numbers = [10, 2, 3, 14, 16, 6, 7, 9]; 

let newArray = numbers.filter((num) => {
      return num >= 10; // our condition

console.log(newArray); // prints [10, 14, 16]

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: 

var pilots = [
        {name: "sebastian vettel", team: "ferrari"},
        {name: "lewis hamilton",          team: "mercedes"},
        {name: "gasly",                                          team: "red bull racing"},

var championship =  pilots.filter(function(pilot) {
        return == "ferrari";

// return {name: "sebastian vettel", team: "ferrari"}


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


Please enter your comment!
Please enter your name here