How to effectively use the filter() method in Javascript

Updated: February 19, 2023 By: Khue Post a comment

This concise and straightforward article shows you how to effectively use the filter() method in Javascript.

The Fundamentals

The filter() method is used to extract values from an array based on a specified condition. It takes a callback function that is executed for each element in the array, and if the callback function returns true, the element is included in the resulting array. Otherwise, the element is excluded.

Here’s the syntax that uses an arrow callback function:

newArray = oldArray.filter((element, index, array) => {
  // return true or false to include or exclude the element
}, thisArg);

Where:

  • oldArray: The array to be filtered
  • newArray: The new array that contains all the elements that pass the test implemented by the provided callback function. The original array will be intact.
  • (element, index, array) => {}: A function that can take up to 3 arguments:
    • element: The current element being processed in the array.
    • index (optional): The index of the current element being processed in the array.
    • array (optional): The array on which filter() was called.
    • The arrow function should return a boolean value indicating whether the element should be included in the resulting array or not.
  • thisArg (optional): The value to be used as this when executing the arrow function. It can be useful when working with object methods that use this to refer to the object itself.

If you don’t like modern arrow functions, you can use a traditional callback function like this:

array.filter(function(element, index, array) {
  // return true or false to include or exclude the element
}, thisArg);

You should avoid modifying the original array (or oldArray) inside the callback function, as this can lead to unexpected outcomes.

Now, it’s time to get our hands dirty by writing some code.

Real-World Examples

Filtering numbers

In this example, we’ll get all even numbers from a given array.

The code:

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12];

// Filter out all even numbers
const evenNumbers = numbers.filter(function(num) {
  return num % 2 === 0;
});

console.log(evenNumbers); 

Output:

[ 2, 4, 6, 8, 10, 12 ]

Filtering strings

Let’s say we have an array of words. Our job is to filter out long words (length > 6).

The code:

const words = [
  'apple',
  'banana',
  'cherry',
  'dog',
  'slingacademy.com',
  'maidenless',
];

const longWords = words.filter((word) => word.length > 6);

console.log(longWords);

Output:

[ 'slingacademy.com', 'maidenless' ]

Filtering objects

Filtering objects is the most common task you may have to deal with when working on real-world projects. In the following example, we have an array of fictitious productions and what we will do is to filter products whose price is less than 10000.

The code:

const products = [
    { name: 'laptop', price: 43000, brand: 'lenovo', color: 'silver' },
    { name: 'phone', price: 15000, brand: 'apple', color: 'gray' },
    { name: 'watch', price: 3000, brand: 'casio', color: 'black' },
    { name: 'sunglass', price: 800, brand: 'rayban', color: 'black' },
    { name: 'camera', price: 40000, brand: 'canon', color: 'gray' },
]

// filter products whose price is less than 10000
const cheap = products.filter(product => product.price <= 10000);

console.log(cheap);

Output:

[
  { name: 'watch', price: 3000, brand: 'casio', color: 'black' },
  { name: 'sunglass', price: 800, brand: 'rayban', color: 'black' }
]

What about the “thisArg” argument?

In the examples above, we have never used the second parameter of the filter() method. Let’s see how to do it in the example below:

const myObject = {
  data: [10, 15, 20, 25, 30],
  minValue: 20,
  // don't use arrow function here because it doesn't have its own this
  filterData: function () {
    return this.data.filter(function (item) {
      // only return items that are greater than or equal to minValue
      return item >= this.minValue;
    }, this);
  },
};

const filteredData = myObject.filterData();

console.log(filteredData);

Output:

[ 20, 25, 30 ]

Code explained:

  • We have an object called myObject with a property named data that is an array of numbers. We also have a method called filterData that returns a new array with only the elements in data that are greater than or equal to minValue.
  • Inside the filter() method, we access the minValue property of the myObject object by using this.

Defining the callback function before calling the filter() method

If the callback function is complex and may be used many times in the future, we can define it before using the filter() method.

Example:

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];

// test if a number is prime or not
const isPrime = (num) => {
  for (let i = 2; i < num; i++) if (num % i === 0) return false;
  return num > 1;
};

// get the prime numbers
const primes = numbers.filter(isPrime);

console.log(primes);

Output:

[ 2, 3, 5, 7, 11, 13 ]

Note: A prime number is a number that is only divisible by 1 and itself.