Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

How to filter object array based on attributes?

  • Last Updated : 02 Nov, 2020

One can use 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.


Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it's lowest price ever!

var 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 array to derive the elements from array that satisfy the given condition.


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

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

Example 2: The following example shows filtering invalid entries from 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 filter() function on the array of size 9, we get 4 valid (non-zero and numeric) id and 5 invalid id

My Personal Notes arrow_drop_up
Recommended Articles
Page :