Open In App
Related Articles

How to filter object array based on attributes?

Improve Article
Save Article
Like Article

One can use the filter() function in JavaScript to filter the object array based on attributes. The filter() function will return a new array containing all the array elements that pass the given condition. If no elements pass the condition it returns an empty array. The filter() function loops or iterate over each array element and pass each element to the callback function.


let newArray = array.filter(function(item)
      return conditional_statement;

Note: The filter() function does not change the original array.

Example 1: We create an array of “students” and call the filter() function on the array to derive the elements from the array that satisfy the given condition.


let obj = {
    'Students': [{
        "name": "Raj",
        "Age": "15",
        "RollNumber": "123",
        "Marks": "99",
    }, {
        "name": "Aman",
        "Age": "14",
        "RollNumber": "223",
        "Marks": "69",
        "name": "Vivek",
        "Age": "13",
        "RollNumber": "253",
        "Marks": "89",
let newArray = obj.Students.filter(function (el) {
    return el.Age >= 15 &&
        el.RollNumber <= 200 &&
        el.Marks >= 80;

Output: After applying the filter function on the array, we get the first element of the array as output as it satisfies the given condition.

:{name: 'Raj', Age: '15', RollNumber: '123', Marks: '99'}

Example 2: The following example shows filtering invalid entries from the array. We create an array of “id”s and call the filter() function on the array to derive the “id”s whose values are non-zero and numeric. 


let array = [
    { id: 3 },
    { id: -1 },
    { id: 0 },
    { id: 15 },
    { id: 12.2 },
    { id: null },
    { id: NaN },
    { id: 'undefined' }
let countInvalidEntries = 0
function filterById(obj) {
    if (Number.isFinite( && !== 0) {
        return true
    return false;
let arrayById = array.filter(filterById);
console.log('Filtered Array with non-zero and numeric id: \n',
console.log('Number of Invalid Entries = ', countInvalidEntries);

Output: After applying the filter() function on the array of size 9, we get 4 valid (non-zero and numeric) id and 5 invalid id

Filtered Array with non-zero and numeric id: 
 (4) [{…}, {…}, {…}, {…}]
Number of Invalid Entries =  5

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 16 May, 2023
Like Article
Save Article
Similar Reads
Complete Tutorials