Filtering and Mapping Objects in JavaScript

To understand filtering and mapping objects in javascript, we will work on an example. At the very first step we have a users array, filled with objects. We plan to create a function (getActiveUserGreetings). We first filter to keep the active users and than return a new object for each.


const users = [
  { name: "Alice", age: 28, isActive: true },
  { name: "Bob", age: 35, isActive: false },
  { name: "Charlie", age: 22, isActive: true },
  { name: "Diana", age: 40, isActive: false }
];

function getActiveUserGreetings(users) {
  return users
    .filter(user => user.isActive) // Step 1: Keep only active users
    .map(user => ({                 // Step 2: Return a new object for each
      name: user.name,
      message: `Hello, ${user.name}!`
    }));
}

// Example usage:
const activeGreetings = getActiveUserGreetings(users);

console.log(activeGreetings);

JavaScript
Can I chain filter() and map() like this?

Yes! Both return new arrays, so you can safely chain them. The filter runs first to narrow down the data, then map transforms the filtered result.

What happens if I reverse the order?

If you run .map() before .filter(), you’ll be transforming every user (even the inactive ones) — which is usually not what you want.

Is this efficient for large datasets?

Yes, chaining filter() and map() is quite performant for most use cases. For very large datasets, consider using streams or pagination strategies if needed.

Leave a Reply

Your email address will not be published. Required fields are marked *