Monday, December 30, 2024
Google search engine
HomeLanguagesHow to filter object array based on attributes?

How to filter object array based on attributes?

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.

Syntax:

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.

Javascript




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;
}
);
console.log(newArray);


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.

[{…}]
0
:{name: 'Raj', Age: '15', RollNumber: '123', Marks: '99'}
length
:1
[[Prototype]]
:Array(0)

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. 

Javascript




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(obj.id) && obj.id !== 0) {
        return true
    }
    countInvalidEntries++
    return false;
}
 
let arrayById = array.filter(filterById);
 
console.log('Filtered Array with non-zero and numeric id: \n',
    arrayById);
 
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

RELATED ARTICLES

Most Popular

Recent Comments