Using map, reduce, filter

  • Last updated on 7th Apr 2023

Introduction

These functions are some of the most natively and explicitly used functions in our toolbelt. Whether it’s rendering a list of items with transformations, handling search functionality, or dealing with pagination data on the frontend. The same for backend; processing API responses, aggregating data, or sorting it. But in this article, we’ll focus on how these work at the base level. First isolated, then combined altogether.

map

// Example array
const numbers = [1, 2, 3, 4, 5];

// Double each number
const doubledNumbers = numbers.map(number => number * 2);

console.log(doubledNumbers); // Output: [2, 4, 6, 8, 10]

Again, we have the same array called numbers. We create a variable called doubledNumbers. Inside it, the map function takes each number in the numbers array and multiplies it by 2. This results in the new array [2, 4, 6, 8, 10]. Then it’s logged.

reduce

// Example array
const numbers = [1, 2, 3, 4, 5];

// Sum all numbers
const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);

console.log(sum); // Output: 15

Above, we have the same array. The reduce method takes two arguments: a function and an initial value (0 in our case). The function itself has two parameters: accumulator and currentValue. The accumulator starts at the initial value (0) and accumulates the sum as the reduce method iterates through each currentValue in the array.

For each element in the array, the currentValue is added to the accumulator. Finally, reduce returns the total sum, which is stored in the variable sum. When we log sum to the console, it outputs 15.

filter

// Example array
const numbers = [1, 2, 3, 4, 5];

// Double each number
const doubledNumbers = numbers.map(number => number * 2);

console.log(doubledNumbers); // Output: [2, 4, 6, 8, 10]

Again, we have the same array called numbers. We create a variable called doubledNumbers. Inside it, the map function takes each number in the numbers array and multiplies it by 2. This results in the new array [2, 4, 6, 8, 10]. Then it’s logged.

// Example array
const numbers = [1, 2, 3, 4, 5];

// Filter out odd numbers
const evenNumbers = numbers.filter(number => number % 2 === 0);

console.log(evenNumbers); // Output: [2, 4]

Above, we have a sample array of numbers [1, 2, 3, 4, 5, 6]. We use the filter method to create a new array called evenNumbers. The method goes through each number in the original array. Applying the logic: A number is even if it leaves a remainder of 0 when divided by 2. Then it’s filtered out and only the even numbers are logged.

Combined

// Array of burger orders
const orders = [
    { name: "Classic Burger", price: 8 },
    { name: "Cheeseburger", price: 6 },
    { name: "Veggie Burger", price: 4 },
    { name: "Bacon Burger", price: 7 },
    { name: "Chicken Burger", price: 5 }
];

// Filter out orders less than $5
const filteredOrders = orders.filter(order => order.price >= 5);

// Apply a 10% discount to remaining orders
const discountedOrders = filteredOrders.map(order => ({
    name: order.name,
    price: order.price * 0.9
}));

// Calculate the total revenue from discounted orders
const totalRevenue = discountedOrders.reduce((total, order) => total + order.price, 0);

console.log(filteredOrders);
// Output: [
//   { name: "Classic Burger", price: 8 },
//   { name: "Cheeseburger", price: 6 },
//   { name: "Bacon Burger", price: 7 },
//   { name: "Chicken Burger", price: 5 }
// ]

console.log(discountedOrders);
// Output: [
//   { name: "Classic Burger", price: 7.2 },
//   { name: "Cheeseburger", price: 5.4 },
//   { name: "Bacon Burger", price: 6.3 },
//   { name: "Chicken Burger", price: 4.5 }
// ]

console.log(`Total Revenue: $${totalRevenue.toFixed(2)}`); // Output: Total Revenue: $23.40

Above, we have a burgershop that calculates the total revenue from the discounted orders. We have an array of orders. All having the name of the burger and its price. We want to filter out orders that are less than $5 and apply a 10% discount to all remaining orders. Finally, we’ll calculate the total revenue from these discounted orders.

We start by filtering out any orders that are less than $5 because we’re focusing on higher-value items. Then we apply the 10% discount to each remaining order. In the end, we then sum up the prices of all discounted orders to get the total revenue.

Resources