JavaScript Array .filter() method

The JavaScript array .filter() method is used to create a new array containing the array items that validates a condition or a test. From the term itself "filter", it filters the array just to get the desired one's.

This array.filter() built-in JavaScript function accepts a callback function that we can use to get every item on each iteration of the array.

The callback function contains the current iterated item, the current index and the copy of the array itself on each iteration.

Array .filter() Method Syntax

This is how you can use the the .filter() method.


  array.filter((item, index, array) => {
    // run your test here and make sure to return true or false
  })

Array .filter() Method on Array of Objects


  const strawHats = [
    { name: "Mugiwara Luffy", gender: "male", fruit: "🍉" },
    { name: "Zoro Marimo", gender: "male", fruit: "🍌" },
    { name: "Nami Swan", gender: "female", fruit: "🍌" },
  ];

  const likesBanana = ninjas.filter((ninja) => {
    return ninja.fruit === "🍌";
  });

  console.table(likesBanana);

So, we have an array above named strawHats that contains basic information about a member - name, gender and favorite fruit.

Now, we want to filter out any member that likes to eat a banana (🍌). With .filter() method being used to do that, the output of our code on the console would be like this:


  [
    {
        "name": "Zoro Marimo",
        "gender": "male",
        "fruit": "🍌"
    },
    {
        "name": "Nami Swan",
        "gender": "female",
        "fruit": "🍌"
    }
    
]

Watch Tutorial

Here's a quick video tutorial about the JavaScript array .filter() method.