Home > Article > Web Front-end > How to Filter an Array of Objects in JavaScript?
Filter an Array of Objects in JavaScript
Given an array of objects, it's often necessary to search and filter them based on specific criteria. Here's how to filter an array of objects in JavaScript, focusing on finding objects where name equals "Joe" and age is less than 30.
Array.prototype.filter() Method:
The Array.prototype.filter() method allows you to create a new array by filtering the original array based on a given function. In our case, the function would compare the object's name and age to the criteria.
This solution uses an arrow function (ES6) to test each element in the array. If both the name and age conditions are met, the element will be included in the new array.
jQuery.grep() Function:
If you're using jQuery, you can also use the jQuery.grep() function to perform the filtering.
jQuery.grep() takes an array and a callback function as arguments. The callback function, similar to the arrow function in the first solution, evaluates each element in the array against the specified conditions.
The above is the detailed content of How to Filter an Array of Objects in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!