How to filter nested array object?

🔍 What is it?

  • Filtering a nested array object involves extracting specific elements from an array of objects based on certain criteria.

❓ How is it used?

  1. Iterate through the main array containing nested objects.
  2. For each nested object, apply a filtering condition to select the desired elements.
  3. Construct a new array containing only the filtered elements.

Why is it needed?

  • Filtering nested array objects allows developers to extract relevant data from complex data structures, enabling efficient data manipulation and analysis.

Examples:

  • Suppose we have an array of users, each containing an array of their posts. We want to filter out only the posts made by users with a certain age.
const users = [
  { name: 'John', age: 25, posts: [{ title: 'Post 1' }, { title: 'Post 2' }] },
  { name: 'Alice', age: 30, posts: [{ title: 'Post 3' }, { title: 'Post 4' }] }
];
// Filter posts made by users with age greater than 25  

const filteredPosts = users.flatMap(user => user.posts.filter(post => user.age > 25));

console.log(filteredPosts);

Output:

[
  { title: 'Post 3' },
  { title: 'Post 4' }
]

In this example, we filtered out posts made by users with an age greater than 25.

This process involves iterating through the main array (users), accessing each nested array of posts, and applying the filtering condition to select relevant posts.