How to Filter an array of objects in javascript?- A Complete Tutorial

0

 

How to Filter an array of objects in javascript



If you've been working with JavaScript for a while, you've definitely come across arrays of objects. Whether you're dealing with a list of users, products, blog posts, or anything else — filtering this data is something you'll do a lot.

In this article, I’m going to walk you through how to filter an array of objects in JavaScript — and we’ll go even deeper by handling nested arrays, multiple arrays, and even unique values.



 

 

What is the filter() Method in JavaScript?

Before starting lets us get a clear picture of whats is filter method

The filter() method is used to create a new array from an existing one, but only with the elements that match a certain condition.

In simple words:

You give it a test, and it gives you only the items that pass the test.



const newArray = originalArray.filter(callback);


const newArray = originalArray.filter(callback);

  • callback is a function that returns true or false for each item.
  • If it returns true, the item stays.
  • If it returns false, the item is removed.

 


 

How to Filter an Array of Objects in JavaScript


Imagine you’re organizing a virtual tech meetup . You have a list of registered users from different countries, but now you want to send a reminder email only to the folks from India 🇮🇳.

Here’s the data you have:


const users = [ { name: "Alok", country: "India" }, { name: "Emma", country: "USA" }, { name: "Ravi", country: "India" } ];



So how do we get just the users from India?
This is where the magical filter() method steps in.


const indians = users.filter(user => user.country === "India");

console.log(indians);


Output:


[ { name: "Alok", country: "India" }, { name: "Ravi", country: "India" } ]



What Just Happened?

Let’s break it down like we’re explaining it to a friend:

  • .filter() goes through the array one object at a time.
  • For each user, it checks if user.country === "India".
  • If that’s true, the user gets added to the new array.
  • If it’s false, the user is politely left out. 

Think of filter() like a bouncer at a club. You tell the bouncer, “Only people from India are allowed in tonight,” and it does exactly that.

 

 


 

How to Filter Two Arrays of Objects in JavaScript ?


Let’s say you’re running a website and have two groups:

  • A list of all users
  • A list of banned users who should not be allowed on the platform

Your task: Remove the banned users from the main user list. Here's the data:


const users = [ { id: 1, name: "Alok" }, { id: 2, name: "Emma" }, { id: 3, name: "Ravi" } ]; const banned = [ { id: 2 }, { id: 3 } ];



You want to filter out the users whose id exists in the banned list.


 The Solution (Code)


const allowedUsers = users.filter(user => !banned.some(b => b.id === user.id) );


 

console.log(allowedUsers);

Output:


[

  { id: 1, name: "Alok" }

]


 

What’s Happening Behind the Scenes?

Let’s break this down line by line:

Step 1: users.filter(...)

This goes through each user one-by-one. You give it a test condition, and it will keep only the users that pass that test.


Step 2: banned.some(b => b.id === user.id)

This checks the banned list for a match.
.some() means:

“Is there at least one banned user whose id is equal to this user's id?”

If the answer is:

  •  Yes → the user is banned
  •  No → the user is safe

Step 3: !banned.some(...)

We put a ! (not) in front to reverse the result.

So now the logic becomes:

“Keep this user only if they are not found in the banned list.”




 How to Filter Nested Array of Objects in JavaScript?


Sometimes your data isn’t just a flat list.
It’s nested — like a box inside another box.

The Scenario

Imagine you’re managing teams in a company. Each team has multiple members, and you want to filter out members who are younger than 25.

Here’s your data:


const teams = [ { name: "Team A", members: [ { name: "Alok", age: 25 }, { name: "Ravi", age: 30 } ] }, { name: "Team B", members: [ { name: "Kiran", age: 22 }, { name: "Riya", age: 19 } ] } ];



Your Goal:

Get a list of all members from all teams who are younger than 25.

 The Solution:


const youngMembers = teams.flatMap(team => team.members.filter(member => member.age < 25) ); console.log(youngMembers);



 Output:


[ { name: "Kiran", age: 22 }, { name: "Riya", age: 19 } ]


What’s Going On Here?

Let’s break it down in a human-friendly way:

1. team.members.filter(...)

  • We're saying: "Hey team, give me just your young members (under 25)."
  • This runs for each team individually.

2. .flatMap(...)

  • Now we have many filtered results, one from each team.
  • flatMap() combines all those into one flat array, so we don’t end up with results like [[members], [members]].



 How to Filter Unique Array of Objects in JavaScript?

Sometimes, you have an array of objects, and some of the objects are duplicates — they have the same values for one or more properties. You want to remove those duplicates and keep only the unique ones.


Let’s See an Example First


const users = [ { id: 1, name: "Alok" }, { id: 2, name: "Emma" }, { id: 1, name: "Alok" }, // duplicate ];


Here, we want to remove the second { id: 1, name: "Alok" } because it’s a duplicate.


Simple Way to Filter Unique Objects (by id)

You can use .filter() along with a Set to keep track of what you've already seen.


const uniqueUsers = []; const seen = new Set(); users.forEach(user => { if (!seen.has(user.id)) { seen.add(user.id); uniqueUsers.push(user); } }); console.log(uniqueUsers);



  Even Shorter Version (Using .filter())


const unique = users.filter((user, index, self) => index === self.findIndex(u => u.id === user.id) );



 Here’s what’s happening:

  • self.findIndex(...) finds the first object with that id.
  • If the current index is the first one — keep it.
  • If it’s a duplicate later in the array — skip it.



How to Filter Array of objects by property value?


 Imagine you have a list of products — phones, laptops, tablets — and each product has a property like inStock which tells you if it's available.

Now you want to get only those products that are currently in stock.


 Example:


const products = [ { name: "Phone", inStock: true }, { name: "Laptop", inStock: false }, { name: "Tablet", inStock: true } ];



In this case:

  • The Phone and Tablet are available (inStock: true)
  • The Laptop is not (inStock: false)


Let’s Filter the In-Stock Products


const available = products.filter(p => p.inStock);


 Here's what's happening:

  • .filter() goes through every product in the array.
  • It checks if p.inStock is true.
  • If yes, it keeps that product in the result.


🖨 Output:


console.log(available);



Gives:


[ { name: "Phone", inStock: true }, { name: "Tablet", inStock: true } ]



 You now have a new array with only the products that are in stock!

Why This Is Useful?

This is super handy when working with:

  • Product lists (in-stock/out-of-stock)
  • Users (active/inactive)
  • Tasks (completed/not completed)
  • Any data where you want to pick only the ones matching a certain condition

 

 

 


 

Conclusion

Filtering arrays of objects in JavaScript is a common and useful task — and the .filter() method makes it easy.

You can use it to:

  • Get items matching a specific value
  • Remove duplicates
  • Or apply more complex filtering logic

Just combine filter() with methods like includes(), some(), or findIndex() when needed.

Hope this has worked for you and made things clearer!

 

Tags

Post a Comment

0 Comments
Post a Comment (0)
To Top