#Javascript

How To Use filter() In Javascript

Javacript Filter

The filter() method is a native JavaScript array function that allows you to create a new array containing only the elements that meet a specific condition. It is an immutable function, meaning it does not modify the original array.

In simple terms, as the method name suggests, filter() is used to filter an array, keeping only the elements that satisfy the filtering condition.

Filter Syntax

JavaScript
const newArray = originalArray.filter((element, index, array) => {
    return condition;
});
JavaScript
  • element – The current element of the array.
  • index (optional) – The index of the current element.
  • array (optional) – The original array itself.
  • condition – An expression that returns true for the elements that should be included in the new array.

Examples of using filter()

1. Filtering numbers greater than a given value

JavaScript
const numbers = [10, 5, 8, 1, 20, 15];
const greaterThanTen = numbers.filter(num => num > 10);
console.log(greaterThanTen); // [20, 15]
JavaScript

2. Filtering objects inside an array

Imagine an array of objects representing users, and we want to find only those who are of legal age.

JavaScript
const users = [
    { name: "Andrew", age: 25 },
    { name: "Kevin", age: 17 },
    { name: "Peter", age: 30 },
    { name: "John", age: 15 }
];

const adults = users.filter(user => user.age >= 21);
console.log(adults);
JavaScript

Output

JavaScript
[
    { name: "Andrew", age: 25 },
    { name: "Peter", age: 30 }
]
JavaScript

3. Removing falsy values from an array

In JavaScript, values such as 0, "", null, undefined, and false are considered falsy. We can remove these values from an array using filter():

JavaScript
const values = [0, "", 5, "JavaScript", null, undefined, 10, false];
const validValues = values.filter(Boolean);
console.log(validValues); // [5, "JavaScript", 10]
JavaScript

4. Filtering elements in an array of strings

We can use filter() to search for words that contain a specific letter:

JavaScript
const words = ["banana", "apple", "orange", "grape"];
const wordsWithR = words.filter(word => word.includes("r"));
console.log(wordsWithR); // ["orange", "grape"]
JavaScript

Difference Between filter(), map(), and reduce()

  • filter(): Returns a new array with elements that meet a condition.
  • map(): Returns a new array by transforming the original elements.
  • reduce(): Reduces the array to a single value by combining its elements.

Comparative example:

JavaScript
const numbers = [1, 2, 3, 4, 5];

const evens = numbers.filter(num => num % 2 === 0); // [2, 4]
const doubled = numbers.map(num => num * 2); // [2, 4, 6, 8, 10]
const sum = numbers.reduce((acc, num) => acc + num, 0); // 15
JavaScript

Is filter() always necessary?

What’s the advantage of using filter() if I can just iterate over the array and create a new one? The main reason is to improve readability and keep a functional-style pattern in your code.

Analyze the code samples below:

JavaScript
// Example 1
const newArray = [];
const originalArray = [1,2,3,4,5,6,7,8,9,10];

for (let i = 0; i < originalArray.length; i++) {
  if (originalArray[i]%2 === 0) {
    newArray.push(originalArray[i]);
  }
}

// Example 2
const originalArray = [1,2,3,4,5,6,7,8,9,10];
const newArray = originalArray.filter((elem) => elem%2 === 0);

// Example 3
const isEven = (n) => n%2 === 0;

const originalArray = [1,2,3,4,5,6,7,8,9,10];
const newArray = originalArray.filter(isEven);
JavaScript

The first example uses a simple for loop to iterate over the array and manually insert elements into a new one. The second approach is much more concise and easier to understand. In the third case, where an external function is used to validate each element, the filter() syntax becomes even simpler.

So, in general terms, using a utility function like Array.filter() is recommended to simplify the source code, but we should be careful not to overuse it.

When should you use filter()?

  • When you need to extract specific elements from an array.
  • When you want to maintain data immutability.
  • When you want to remove unwanted values from an array without modifying the original one.

Conclusion

filter() is one of the most powerful functions for array manipulation in JavaScript. Using it allows you to write cleaner, more readable, and more efficient code. Now that you understand how it works, try applying it in your own projects!

Read More

Official MDN documentation on filter()

How To Use filter() In Javascript

Introduction to Data Structures

How To Use filter() In Javascript

A New DeepSeek Paper Highlights the Growing

Leave a comment

Your email address will not be published. Required fields are marked *