How to filter object array based on attributes?
To filter an array of objects by attribute, Array.prototype.filter
method comes to rescue. Consider you have objects with isActive: true
and you want to separate them:
In the .filter()
function, an arrow function checks if isActive
attribute is true.
Sifting through multiple attributes
Combining conditions for precision
When more than one condition is required, combine them with logical operators:
Jokes aside, mind your types!
Don't ignore type of the values during string and number comparison:
Supporting elderly browsers
Providing support for Internet Explorer? A polyfill for Array.prototype.filter
enhances the compatibility:
Mastery of object filtering with jLinq
jLinq equips you for chaining filter conditions for more complex queries:
Further exploiting the filter
Ensuring immutability for peace of mind
Saving the outcome in a constant, further ensures immutable filtered array:
Readability matters
While chaining conditions or invoking methods, proper indentation bestows readability:
Resorting to older but trustworthy methods
jQuery
's .map()
function steps in as an alternative method:
A practical application with JSFiddle
Check this jsfiddle link for a live demo of the filter operation:
Was this article helpful?