DEV Community

Cover image for Using Map, Filter, and Reduce Effectively in JavaScript🔥
Hossein Mobarakian
Hossein Mobarakian

Posted on

Using Map, Filter, and Reduce Effectively in JavaScript🔥

JavaScript’s map(), filter(), and reduce() are essential tools for working with arrays, especially when dealing with arrays of objects. They let you write clean, functional code for transforming, filtering, and aggregating data. Here’s how you can use them effectively:


1. map() – Transforming Data

The map() method is perfect for creating new arrays by transforming each element.

đź“Ś Use Case: Extracting or reformatting object properties.

Examples:

const products = [
  { name: 'Laptop', price: 1000 },
  { name: 'Phone', price: 500 },
  { name: 'Tablet', price: 700 },
];

// Example 1: Extract product names
const productNames = products.map(product => product.name);
console.log(productNames); // ['Laptop', 'Phone', 'Tablet']

// Example 2: Apply a discount to all prices
const discountedProducts = products.map(product => ({
  ...product,
  price: product.price * 0.9,
}));
console.log(discountedProducts);
// [
//   { name: 'Laptop', price: 900 },
//   { name: 'Phone', price: 450 },
//   { name: 'Tablet', price: 630 }
// ]
Enter fullscreen mode Exit fullscreen mode

2. filter() – Picking the Right Data

Use filter() to create a subset of data based on a condition.

đź“Ś Use Case: Filtering objects based on their properties.

Examples:

const employees = [
  { name: 'Alice', role: 'Developer' },
  { name: 'Bob', role: 'Designer' },
  { name: 'Charlie', role: 'Developer' },
];

// Example 1: Filter developers
const developers = employees.filter(employee => employee.role === 'Developer');
console.log(developers);
// [
//   { name: 'Alice', role: 'Developer' },
//   { name: 'Charlie', role: 'Developer' }
// ]

// Example 2: Filter employees whose names start with 'A'
const namesStartingWithA = employees.filter(employee => employee.name.startsWith('A'));
console.log(namesStartingWithA);
// [{ name: 'Alice', role: 'Developer' }]
Enter fullscreen mode Exit fullscreen mode

3. reduce() – Combining Data

The reduce() method aggregates data from an array into a single value or object.

đź“Ś Use Case: Summing values or building new structures.

Examples:

const orders = [
  { id: 1, amount: 100 },
  { id: 2, amount: 200 },
  { id: 3, amount: 300 },
];

// Example 1: Calculate the total amount
const totalAmount = orders.reduce((total, order) => total + order.amount, 0);
console.log(totalAmount); // 600

// Example 2: Group orders by amount threshold
const groupedOrders = orders.reduce((groups, order) => {
  const category = order.amount > 150 ? 'High' : 'Low';
  groups[category] = groups[category] || [];
  groups[category].push(order);
  return groups;
}, {});
console.log(groupedOrders);
// {
//   Low: [{ id: 1, amount: 100 }],
//   High: [{ id: 2, amount: 200 }, { id: 3, amount: 300 }]
// }
Enter fullscreen mode Exit fullscreen mode

Chaining Example

You can combine these methods to process data step by step.

const users = [
  { name: 'Alice', age: 25, isActive: true },
  { name: 'Bob', age: 30, isActive: false },
  { name: 'Charlie', age: 35, isActive: true },
];

// Get active users, double their age, and calculate the total
const totalAge = users
  .filter(user => user.isActive) // Active users
  .map(user => ({ ...user, age: user.age * 2 })) // Double their age
  .reduce((sum, user) => sum + user.age, 0); // Sum their ages

console.log(totalAge); // 120 (Alice: 50, Charlie: 70)
Enter fullscreen mode Exit fullscreen mode

Why Use These Methods?

  • Efficiency: Perform operations without manual loops.
  • Readability: Your code is easier to understand.
  • Immutability: They don’t modify the original array.

Mastering these methods with arrays of objects will supercharge your JavaScript skills! 🚀 Let me know your favorite use case in the comments! 👇

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

đź‘‹ Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay