JavaScript Filter Function Explained

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 the number 2, so the numbers 3, 4, and 5.

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.

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 object from the ‘people’ array.

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’.

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 and 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.

Leave a Reply