Filter in Javascript
The filter() method creates a new array with all elements that pass a test implemented by the provided function.
Key Concepts
- Returns new array with filtered elements
- Only includes elements that return truthy values
- Can return array of different length
- Great for removing unwanted data
Basic Filter Usage
Code
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; const evenNumbers = numbers.filter(num => num % 2 === 0); console.log(evenNumbers); // [2, 4, 6, 8, 10] const oddNumbers = numbers.filter(num => num % 2 !== 0); console.log(oddNumbers); // [1, 3, 5, 7, 9]
Filter Objects by Property
Filter cars by rating { id: 2, name: "Verna", brand: "Hyundai", make: "2008", rating: 4 }, { id: 3, name: "Bolero", brand: "Mahindra", make: "2012", rating: 5 }, { id: 4, name: "Baleno", brand: "Maruti", make: "2022", rating: 4 }, { id: 6, name: "G-class", brand: "Mercedes", make: "2024", rating: 5 } Get only car names with rating >= 4.
Code
const cars = [ { id: 1, name: "Nexon", brand: "Tata", make: "2017", rating: 2 }, { id: 2, name: "Verna", brand: "Hyundai", make: "2008", rating: 4 }, { id: 3, name: "Bolero", brand: "Mahindra", make: "2012", rating: 5 }, { id: 4, name: "Baleno", brand: "Maruti", make: "2022", rating: 4 }, { id: 5, name: "Seltos", brand: "Kia", make: "2011", rating: 3 }, { id: 6, name: "G-class", brand: "Mercedes", make: "2024", rating: 5 } ]; function filterCarsByRating(cars, minRating) { return cars.filter(car => car.rating >= minRating); } const highRatedCars = filterCarsByRating(cars, 4); console.log(highRatedCars); const highRatedCarNames = cars .filter(car => car.rating >= 4) .map(car => car.name); console.log(highRatedCarNames); // ["Verna", "Bolero", "Baleno", "G-class"]
Filter with Multiple Conditions
Filter electronics that are in stock and price < 40000 [{ name: "Tablet", price: 25000, category: "Electronics", inStock: true }].
Code
const products = [ { name: "Laptop", price: 50000, category: "Electronics", inStock: true }, { name: "Phone", price: 30000, category: "Electronics", inStock: false }, { name: "Tablet", price: 25000, category: "Electronics", inStock: true }, { name: "Book", price: 500, category: "Education", inStock: true } ]; const affordableElectronics = products.filter(product => product.category === "Electronics" && product.inStock && product.price < 40000 ); console.log(affordableElectronics);
Filter with Index
Get elements at even indices.
Code
const numbers2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; const evenIndexElements = numbers2.filter((num, index) => index % 2 === 0); console.log(evenIndexElements); // [1, 3, 5, 7, 9]
Filter Falsy Values
Remove all falsy values Or explicitly.
Code
const mixedArray = [0, 1, false, 2, "", 3, null, undefined, 4, NaN]; const truthyValues = mixedArray.filter(Boolean); console.log(truthyValues); // [1, 2, 3, 4] const truthyValues2 = mixedArray.filter(value => !!value); console.log(truthyValues2); // [1, 2, 3, 4]
Filter Unique Values
Modern approach using Set.
Code
const duplicates = [1, 2, 2, 3, 3, 3, 4, 5, 5]; const uniqueValues = duplicates.filter((value, index, self) => self.indexOf(value) === index ); console.log(uniqueValues); // [1, 2, 3, 4, 5] const uniqueValues2 = [...new Set(duplicates)]; console.log(uniqueValues2); // [1, 2, 3, 4, 5]
Filter with String Operations
Filter words starting with 'a' Filter words longer than 5 characters.
Code
const words = ["apple", "banana", "apricot", "cherry", "avocado"]; const wordsStartingWithA = words.filter(word => word.startsWith("a")); console.log(wordsStartingWithA); // ["apple", "apricot", "avocado"] const longWords = words.filter(word => word.length > 5); console.log(longWords); // ["banana", "apricot", "cherry", "avocado"]
Filter with Array Operations
Filter arrays with length > 2.
Code
const arrays = [[1, 2], [3, 4, 5], [6], [7, 8, 9, 10]]; const longArrays = arrays.filter(arr => arr.length > 2); console.log(longArrays); // [[3, 4, 5], [7, 8, 9, 10]]
Filter with Complex Logic
Filter active admins or users above 25 { id: 1, name: "John", age: 25, active: true, role: "admin" }, { id: 2, name: "Jane", age: 30, active: false, role: "user" }, { id: 4, name: "Alice", age: 35, active: true, role: "admin" }.
Code
const users = [ { id: 1, name: "John", age: 25, active: true, role: "admin" }, { id: 2, name: "Jane", age: 30, active: false, role: "user" }, { id: 3, name: "Bob", age: 20, active: true, role: "user" }, { id: 4, name: "Alice", age: 35, active: true, role: "admin" } ]; const filteredUsers = users.filter(user => (user.active && user.role === "admin") || user.age > 25 ); console.log(filteredUsers);
Custom Filter Implementation
Common Mistakes to Avoid ❌ Don't use filter when you need to transform values Use map instead ❌ Don't forget that filter returns boolean ✅ Always return boolean or truthy/falsy value.
Code
Array.prototype.myFilter = function(callback, thisArg) { const result = []; for (let i = 0; i < this.length; i++) { if (i in this) { // Check if index exists const value = this[i]; if (callback.call(thisArg, value, i, this)) { result.push(value); } } } return result; }; const test = [1, 2, 3, 4, 5].myFilter(num => num % 2 === 0); console.log(test); // [2, 4] const wrong = numbers.filter(num => num * 2); // Returns [1, 2, 3, 4, 5] (all truthy) const correct = numbers.map(num => num * 2); // Returns [2, 4, 6, 8, 10] const wrong2 = numbers.filter(num => { if (num > 3) return num; // Should return boolean }); const correct2 = numbers.filter(num => num > 3); // Returns [4, 5] const correct3 = numbers.filter(num => num % 2 === 0); // Correct
Summary
Understanding filter is essential for mastering javascript. Practice these examples and experiment with variations to deepen your understanding.
Key Takeaways
- filter is a fundamental concept in javascript
- Practice with these examples to build confidence
- Experiment with variations to explore edge cases
- Understanding filter will help you in technical interviews