How to filter out contents in an array in JavaScript?

November 4, 2020 - 3 min read

To filter out contents inside an array, you can use the filter() method in the array in JavaScript.

Let's say we have an array with some fruits names like this,

// array of fruits name
const fruitsArr = ["Apple 🍎", "Avocado 🥑", "Orange 🍊", "Grape 🍇"];

But we don't want all the fruits from this fruitsArr, we just need those fruits whose name starts with the letter A.

So here, we need to filter out fruit's name based on the first letter of fruit. This is a good place to use the filter() method.

// array of fruits name
const fruitsArr = ["Apple 🍎", "Avocado 🥑", "Orange 🍊", "Grape 🍇"];

// using filter() method on the array
// to filter out fruits names.
fruitsArr.filter();

But simply invoking the filter() method doesn't tell it how to do the filtering.

So let's pass a callback function to the filter() method to tell it how to filter.

The callback function will be passed an element from the array which is currently getting looped as the first argument.

// array of fruits name
const fruitsArr = ["Apple 🍎", "Avocado 🥑", "Orange 🍊", "Grape 🍇"];

// using filter() emthod on the array
// to filter out fruits names.
fruitsArr.filter((fruit) => {
  // if the element first letter is "a"
  // then we will return true
  // otherwise we will return false
  if (fruit[0].toLowerCase() === "a") {
    return true;
  } else {
    return false;
  }
});

The callback function needs to return a boolean true for those elements which we want to keep in the array and false for those elements which we do not want in the array.

The filter function doesn't mutate the original array but rather gives us a new array with filtered elements.

So let's make another variable called filteredFruitsArr to contain the filtered fruits like this,

// array of fruits name
const fruitsArr = ["Apple 🍎", "Avocado 🥑", "Orange 🍊", "Grape 🍇"];

// using filter() emthod on the array
// to filter out fruits names.
const filteredFruitsArr = fruitsArr.filter((fruit) => {
  // if the element first letter is "a"
  // then we will return true
  // otherwise we will return false
  if (fruit[0].toLowerCase() === "a") {
    return true;
  } else {
    return false;
  }
});

console.log(filteredFruitsArr); // ["Apple 🍎", "Avocado 🥑"]

We just filtered our fruit array. 🌟

See this example live in JSBin.

Along with the current element, the callback function is passed with optional parameters such as:

  • index of the current element as the second parameter to the callback function
  • the original array where the filter() method is called upon as the third parameter
  • a reference to this when executing the callback

Feel free to share if you found this useful 😃.