The filter function can be used to find elements within an array that match certain criteria. The example below shows an array called 'myNumbers' that contains the numbers 1 through 5. The filter function takes one parameter which is a function that has one parameter. The filter function works by going through each element of the array and checks if a condition matches, if it matches it returns the element. The parameter in the inner function is each element in the array. Then the filter function is used to return all the numbers from that array that are above 2, so the numbers 3, 4, and 5.
var myNumbers = [1, 2, 3, 4, 5];
var result = myNumbers.filter(function(i){ return i > 2 });
Because you pass a function to the filter function you can declare the function elsewhere in the code and then pass that into the filter function. The code snippet below shows creating a function and putting it into the variable 'myFunc'. This allows you to pass the variable, the function, into the filter function. This also means that you could use the same filter function in different areas of the code or multiple times.
var myNumbers = [1, 2, 3, 4, 5];
var myFunc = function(i){ return i > 2; }
var result = myNumbers.filter(myFunc);
You can also use the filter function on any array with any variable types. The below code snippet shows using the filter function on an array of objects. The below code will return a new array with only the first two objects from the original array. This means the variable 'result' will contain the first and second objects from the 'people' array.
var people = [
{firstName: 'John', lastName: 'Smith', age: 32},
{firstName: 'Jane', lastName: 'Doe', age: 27},
{firstName: 'Peter', lastName: 'Hammond', age: 65},
];
var myFunc = function(i){
return i.age < 65;
}
var result = people.filter(myFunc);
All the examples so far are using numbers within the conditional filter function. The below code snippet shows using a string operation in the condition instead. This will return all the objects from the 'people' array whose 'firstName' field begins with the letter 'J'.
var people = [
{firstName: 'John', lastName: 'Smith', age: 32},
{firstName: 'Jane', lastName: 'Doe', age: 27},
{firstName: 'Peter', lastName: 'Hammond', age: 65},
];
var myFunc = function(i){
return i.firstName.startsWith('J');
}
var result = people.filter(myFunc);
The filter function can be used to get specific values from an array and put those values into a new array. It's important to remember that the original array will not be affected in any way, it will contain the same elements before the filter operation after the operation has been executed. If the filter function does not match any items within the array it will return an empty array, as no items matched the criteria so no items will be added to the filtered array.
This post was originally published on https://acroynon.com
Top comments (0)