EN/CH Mode
BRUCE_FE JS Interview Notes - Implement Array Filter Method
Learn how to manually implement JavaScript's Array.filter() method, understand higher-order functions, callback functions, and array processing mechanisms.
EN/CH Mode
Lazy to read articles? Then watch videos!
Array.filter() Method Overview
Array.filter()
is a commonly used array method in JavaScript for creating a new array containing all elements that pass a specific condition test. This method does not modify the original array but returns a new array.
Native Filter Method Usage
// Basic syntax
array.filter(callback(element[, index[, array]])[, thisArg])
// Usage example
const numbers = [1, 2, 3, 4, 5, 6];
const evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers); // [2, 4, 6]
Parameter Description
- 1. callback: Function used to test each element of the array, returns
true
to keep the element - 2. element: The element currently being processed
- 3. index (optional): Index of the current element
- 4. array (optional): The array that called filter
- 5. thisArg (optional): Value to use as this when executing callback
Implement Array.filter() Method
In interviews, implementing Array.filter()
can test understanding of higher-order functions, callback functions, and this binding. Here are the implementation steps:
Basic Implementation
// Basic implementation
Array.prototype.myFilter = function(callback) {
// Check if callback is a function
if (typeof callback !== 'function') {
throw new TypeError(callback + ' is not a function');
}
const result = [];
const length = this.length;
// Iterate through array
for (let i = 0; i < length; i++) {
// Only process valid indices
if (i in this) {
// Call callback function to test condition, keep element if returns true
if (callback(this[i], i, this)) {
result.push(this[i]);
}
}
}
return result;
};
// Usage example
const numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers.myFilter(num => num % 2 === 0);
console.log(evenNumbers); // [2, 4]
Practical Application Examples
Below are several practical applications of the custom filter
method:
1. Filter Object Arrays
const users = [
{ id: 1, name: 'Alice', age: 25, active: true },
{ id: 2, name: 'Bob', age: 17, active: false },
{ id: 3, name: 'Charlie', age: 30, active: true },
{ id: 4, name: 'David', age: 15, active: true },
{ id: 5, name: 'Eve', age: 28, active: false }
];
// Filter active adult users
const activeAdults = users.myFilter(user => user.active && user.age >= 18);
console.log(activeAdults);
// [
// { id: 1, name: 'Alice', age: 25, active: true },
// { id: 3, name: 'Charlie', age: 30, active: true }
// ]
2. Filter Invalid Values
const values = [0, null, undefined, '', false, NaN, 'hello', 42];
// Filter truthy values
const truthyValues = values.myFilter(Boolean);
console.log(truthyValues); // ['hello', 42]
3. Compound Condition Filtering
const products = [
{ id: 1, name: 'Laptop', price: 1200, inStock: true, category: 'electronics' },
{ id: 2, name: 'Book', price: 20, inStock: true, category: 'books' },
{ id: 3, name: 'Phone', price: 800, inStock: false, category: 'electronics' },
{ id: 4, name: 'Monitor', price: 300, inStock: true, category: 'electronics' },
{ id: 5, name: 'Desk', price: 150, inStock: true, category: 'furniture' }
];
// Filter conditions: electronics, in stock, price less than 1000
const availableElectronics = products.myFilter(product =>
product.category === 'electronics' &&
product.inStock &&
product.price < 1000
);
console.log(availableElectronics);
// [
// { id: 4, name: 'Monitor', price: 300, inStock: true, category: 'electronics' }
// ]