This post will discuss how to filter an array in JavaScript. The solution should return an array of all elements that pass a predicate.

1. Using Array.prototype.filter() function

The recommended solution in JavaScript is to use the filter() method, which creates a new array with all elements that pass the predicate function.

The following code example shows how to filter an employee’s object having an age greater than 30.

Download  Run Code

 
You can simplify the code to:

 
You can further shorten the code through ES6 arrow functions.

2. Using Lodash/Underscore Library

Like the JavaScript native filter() method, Underscore and Lodash Library provide their own implementation of the filter() method. You can pass any of the above callback functions to the _.filter method to get the same result.

Download Code

3. Using jQuery

jQuery map() function is often used to transform all array elements to a new array of items. You can use this for filtering an array as well, as demonstrated below:

Download Code

 
Similar to the Array.prototype.filter() method, jQuery Library has grep() method. You can pass any of the above callback functions to the $.grep() method to get the same result and get the array elements that satisfy the specified function.

Download Code

That’s all about filtering an array in JavaScript.