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
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' } ]
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.