Explain Codes LogoExplain Codes Logo

How to filter object array based on attributes?

javascript
filter
array
javascript-8
Alex KataevbyAlex Kataev·Oct 5, 2024
TLDR

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:

const users = [ { name: 'Alice', isActive: true }, { name: 'Bob', isActive: false } ]; const activeUsers = users.filter(user => user.isActive); // Returns: [{ name: 'Alice', isActive: true }]

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:

const products = [ { name: 'Laptop', category: 'Electronics', quantity: 4 }, { name: 'Cheese', category: 'Food', quantity: 0 } //...add more products if you wish ]; const availableElectronics = products.filter(product => product.category === 'Electronics' && product.quantity > 0); // This will spit out all electronic objects that aren't out of stock

Jokes aside, mind your types!

Don't ignore type of the values during string and number comparison:

const items = [ { name: 'Table', price: '150' }, { name: 'Chair', price: '100' } // Who needs chairs, right? ]; const expensiveItems = items.filter(item => Number(item.price) >= 120); // Our chairs only cater exclusively to snobs

Supporting elderly browsers

Providing support for Internet Explorer? A polyfill for Array.prototype.filter enhances the compatibility:

if (!Array.prototype.filter) { Array.prototype.filter = function(func, thisArg) { // ... insert the filter polyfill code here }; // Yes, we are spoon-feeding venerable IE }

Mastery of object filtering with jLinq

jLinq equips you for chaining filter conditions for more complex queries:

const users = [ // ...array of user objects // More users = more problems ]; // Find all users who have a name starting with 'A' and are in their 20s. const result = jlinq.from(users) .startsWith('name', 'A') .less('age', 30) .select(); // Because, why not? Everyone loves twenteens named 'A'

Further exploiting the filter

Ensuring immutability for peace of mind

Saving the outcome in a constant, further ensures immutable filtered array:

const filteredArray = Object.freeze(sourceArray.filter(...)); // This array is as immutable as Mount Rushmore!

Readability matters

While chaining conditions or invoking methods, proper indentation bestows readability:

const filteredUsers = users.filter(user => (user.age >= 20 && user.age <= 30) && user.hobbies.includes('Reading') ); // For the bibliophiles camping in the sweet spot of adulthood

Resorting to older but trustworthy methods

jQuery's .map() function steps in as an alternative method:

const selectedItems = $.map(items, function(item) { if (item.isActive && item.quantity > 0) { return item; } }); // Quite like ordering a pizza with all your favorite toppings, right?!

A practical application with JSFiddle

Check this jsfiddle link for a live demo of the filter operation:

Live example for you: [Filter Objects Demo](https://jsfiddle.net/)