How to Filter Object Array based on Attributes in JavaScript

We can use filter() function to filter an object array based on attributes. 

It returns a new array containing all the array elements that pass the test. If no elements pass the test, an empty array is returned.

Although the find() method can be used by anyone, it returns only the first element that matches the condition, not all matching elements. Therefore, it is not recommended for situations where multiple matches are needed.

Syntax

array.filter(function(currentValue, index, array), thisValue)

Example 1

Visual Representation

Visual Representation of How to Filter Object Array based on Attributes in JavaScript

let actors = [
  { name: 'Eleven', show: 'Stranger Things' },
  { name: 'Jonas', show: 'Dark' },
  { name: 'Mike', show: 'Stranger Things' },
  { name: 'Martha', show: 'Dark' },
  { name: 'Dustin', show: 'Stranger Things' },
]

star = actors.filter(actor => actor.show == 'Stranger Things');
console.log(star);

Output

[
  { name: 'Eleven', show: 'Stranger Things' },
  { name: 'Mike', show: 'Stranger Things' },
  { name: 'Dustin', show: 'Stranger Things' }
]

When the star array is logged to the console using console.log(star), the output will be an array containing only the objects representing actors from ‘Stranger Things’.

Example 2

If you pass null, undefined or  NaN , filter will exclude these special values since they don’t meet the condition.

let actors = [
 { name: 'Eleven', show: 'Stranger Things' },
 { name: 'Jonas', show: NaN },  
 { name: 'Mike', show: null },  
 { name: 'Martha', show: undefined }, 
 { name: 'Dustin', show: '' }, //empty
]

star = actors.filter(actor => actor.show == 'Stranger Things');
console.log(star);

Output

[ { name: 'Eleven', show: 'Stranger Things' } ]

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.