- Published on
Implement Native Filter Function in JS
- Authors

- Name
- Mike Hacker
- @ki5ibd
Usage Context: Employ the custom filter function when you need to create a subset of an array based on specific criteria.
How it works: The filter function generates a new array containing only the elements that satisfy a specified condition. By leveraging a callback function for the condition check, it provides a clean and declarative way to perform selective data extraction, enhancing code readability and maintainability.
Examples:
- Filtering out users who are inactive from a list of user accounts.
- Selecting even numbers from an array of integers.
- Removing null or undefined values from an array.
The provided function filter is a custom implementation of the array filter method in JavaScript. Here’s a detailed explanation of what this function does and the programming principles it utilizes:
Function Explanation
function filter(arr, cb) {
var result = []
for (var i = 0; i < arr.length; i++) {
if (cb(arr[i])) result.push(arr[i])
}
return result
}
What the Function Does:
Initialization:
var result = [];initializes an empty array calledresultwhich will store the elements that pass the test implemented by the callback function.
Iteration:
for (var i = 0; i < arr.length; i++) {starts a loop that iterates over each element in the input arrayarr.
Condition Check and Callback Application:
if (cb(arr[i])) result.push(arr[i]);applies the callback functioncbto the current elementarr[i]. If the callback returnstrue, the current elementarr[i]is pushed into theresultarray.
Return:
return result;returns theresultarray after the loop completes, containing all the elements that passed the test.
Example Usage:
const numbers = [1, 2, 3, 4]
const evenNumbers = filter(numbers, function (num) {
return num % 2 === 0
})
console.log(evenNumbers) // [2, 4]
In this example, the filter function is used to create an array of even numbers from the numbers array.
Programming Principles Utilized
Higher-Order Functions:
- The
filterfunction takes a functioncbas an argument and applies this function to each element in the array to determine if it should be included in the result. This makesfiltera higher-order function because it operates on other functions.
- The
Encapsulation:
- The function encapsulates the logic of filtering an array within a single function, hiding the iteration and condition-checking details from the user. Users only need to provide the condition logic via the callback.
Abstraction:
- This implementation abstracts the process of iterating over an array and applying a condition, allowing users to focus on defining the condition they want to use for filtering.
Immutability:
- The
filterfunction creates a new array (result) and does not modify the original arrayarr. This promotes immutability, as the original data remains unchanged.
- The
Separation of Concerns:
- The logic of what condition to check for each array element (provided by the callback
cb) is separated from the logic of how to iterate over the array and collect results. This separation makes the function more modular and easier to understand.
- The logic of what condition to check for each array element (provided by the callback
Function Composition:
- The custom
filterfunction facilitates function composition, allowing users to chain multiple operations in a readable and maintainable way. It can be used alongside other higher-order functions likemapto perform complex data transformations.
- The custom
