Array Methods: Filter, Map, Reduce

Program demonstrating filter, map, and reduce methods

IntermediateTopic: Array Programs
Back

JavaScript Array Methods: Filter, Map, Reduce Program

This program helps you to learn the fundamental structure and syntax of JavaScript programming.

Try This Code
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

// FILTER: Creates new array with elements that pass test
let evenNumbers = numbers.filter(num => num % 2 === 0);
console.log("Original:", numbers);
console.log("Even numbers (filter):", evenNumbers);

let greaterThan5 = numbers.filter(num => num > 5);
console.log("Numbers > 5:", greaterThan5);

// MAP: Creates new array by transforming each element
let doubled = numbers.map(num => num * 2);
console.log("\nDoubled (map):", doubled);

let squared = numbers.map(num => num ** 2);
console.log("Squared:", squared);

// REDUCE: Reduces array to single value
let sum = numbers.reduce((acc, num) => acc + num, 0);
console.log("\nSum (reduce):", sum);

let product = numbers.reduce((acc, num) => acc * num, 1);
console.log("Product:", product);

// CHAINING: Combine multiple methods
let result = numbers
    .filter(num => num % 2 === 0)  // [2, 4, 6, 8, 10]
    .map(num => num * 2)            // [4, 8, 12, 16, 20]
    .reduce((acc, num) => acc + num, 0); // 60

console.log("\nChained (even * 2, then sum):", result);

// Real-world example: Processing user data
let users = [
    { name: "John", age: 25, active: true },
    { name: "Jane", age: 30, active: false },
    { name: "Bob", age: 20, active: true },
    { name: "Alice", age: 35, active: true }
];

// Get names of active users over 25
let activeOver25 = users
    .filter(user => user.active && user.age > 25)
    .map(user => user.name);

console.log("\nActive users over 25:", activeOver25);

// Calculate average age of active users
let avgAge = users
    .filter(user => user.active)
    .map(user => user.age)
    .reduce((acc, age, index, array) => {
        acc += age;
        if (index === array.length - 1) {
            return acc / array.length;
        }
        return acc;
    }, 0);

console.log("Average age of active users:", avgAge);
Output
Original: [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
Even numbers (filter): [ 2, 4, 6, 8, 10 ]
Numbers > 5: [ 6, 7, 8, 9, 10 ]

Doubled (map): [ 2, 4, 6, 8, 10, 12, 14, 16, 18, 20 ]
Squared: [ 1, 4, 9, 16, 25, 36, 49, 64, 81, 100 ]

Sum (reduce): 55
Product: 3628800

Chained (even * 2, then sum): 60

Active users over 25: [ 'Jane', 'Alice' ]

Average age of active users: 30

Understanding Array Methods: Filter, Map, Reduce

This program demonstrates the three most important array methods in JavaScript.

FILTER: Select Elements

Creates new array with elements that pass test:

arr.filter(item => condition);

Characteristics:

Returns new array
Doesn't mutate original
Returns all matching elements
Returns empty array if none match

MAP: Transform Elements

Creates new array by transforming each element:

arr.map(item => transformation);

Characteristics:

Returns new array
Same length as original
Transforms every element
Can change data type

REDUCE: Accumulate Values

Reduces array to single value:

arr.reduce((acc, item) => {
}, initialValue);
    // accumulate logic
    return newAcc;

Parameters:

-

Accumulator

: Running total/result

-

Current value

: Current element

-

Initial value

: Starting accumulator

CHAINING METHODS

Combine multiple methods:

arr.filter(...).map(...).reduce(...);

Execution order:

1.Filter runs first (filters array)
2.Map runs on filtered result
3.Reduce runs on mapped result

Real-world Example

Processing user data:

users
    .filter(user => user.active)      // Select active
    .map(user => user.age)            // Get ages
    .reduce((acc, age, i, arr) => {   // Calculate average
        acc += age;
    }, 0);
        return i === arr.length - 1 ? acc / arr.length : acc;

When to Use:

-

Filter

: Select subset of elements

-

Map

: Transform all elements

-

Reduce

: Aggregate to single value

-

Chain

: Complex data processing

Performance:

All methods: O(n) time
Chaining: Multiple passes (but readable)

Best Practices:

Use arrow functions for clarity
Chain methods for readability
Don't mutate original arrays
Use meaningful variable names

Let us now understand every line and the components of the above program.

Note: To write and run JavaScript programs, you need to set up the local environment on your computer. Refer to the complete article Setting up JavaScript Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your JavaScript programs.

Table of Contents