Skip to main content

Command Palette

Search for a command to run...

πŸš€ Map, Filter & Reduce in JavaScript + Their Polyfills (with Examples)

Map, Filter & Reduce

Published
β€’4 min readβ€’View as Markdown
πŸš€ Map, Filter & Reduce in JavaScript + Their Polyfills (with Examples)

JavaScript provides powerful array methods like map, filter, and reduce, which help developers write cleaner and more functional code.

In this blog, we’ll break down each method with simple examples and then create custom polyfills to understand how they work under the hood.
Let’s dive in! πŸ‘‡


πŸ”Ή 1. Map in JavaScript

The map() method creates a new array by transforming each element of the original array.

βœ… Example

const employees = [
    { name: 'John', age: 32 },
    { name: 'Sarah', age: 28 },
    { name: 'Michael', age: 40 },
];

const employeesName = employees.map(employee => employee.name);
console.log(employeesName); // ["John", "Sarah", "Michael"]

πŸ› οΈ Polyfill for map()

A polyfill adds support for features that might not exist in older browsers.

if (!Array.prototype.myMap) {
    Array.prototype.myMap = function (callback) {
        const result = [];
        for (let i = 0; i < this.length; i++) {
            result.push(callback(this[i], i, this));
        }
        return result;
    };
}

const myEmployeesName = employees.myMap(employee => employee.name);
console.log(myEmployeesName); // ["John", "Sarah", "Michael"]

πŸ”Ή 2. Filter in JavaScript

The filter() method returns a new array containing only elements that satisfy a condition.

βœ… Example

const products = [
    { name: 'iPhone', price: 999, inStock: true },
    { name: 'Samsung Galaxy', price: 899, inStock: false },
    { name: 'Google Pixel', price: 799, inStock: true },
];

const availableProducts = products.filter(product => product.inStock);
console.log(availableProducts);

πŸ› οΈ Polyfill for filter()

if (!Array.prototype.myFilter) {
    Array.prototype.myFilter = function (callback) {
        const result = [];
        for (let i = 0; i < this.length; i++) {
            if (callback(this[i], i, this)) {
                result.push(this[i]);
            }
        }
        return result;
    };
}

const myAvailableProducts = products.myFilter(product => product.inStock);
console.log(myAvailableProducts);

πŸ”Ή 3. Reduce in JavaScript

The reduce() method reduces an array to a single value (sum, product, max, etc.).

βœ… Example

const orders = [
    { product: 'iPhone', price: 999, quantity: 2 },
    { product: 'Samsung Galaxy', price: 899, quantity: 1 },
    { product: 'Google Pixel', price: 799, quantity: 3 },
];

const totalAmount = orders.reduce((acc, order) => {
    return acc + order.price * order.quantity;
}, 0);

console.log(totalAmount); // 5294

πŸ› οΈ Polyfill for reduce()

if (!Array.prototype.myReduce) {
    Array.prototype.myReduce = function (callback, initialValue) {
        let accumulator = initialValue === undefined ? this[0] : initialValue;
        for (let i = initialValue === undefined ? 1 : 0; i < this.length; i++) {
            accumulator = callback(accumulator, this[i], i, this);
        }
        return accumulator;
    };
}

const myTotalAmount = orders.myReduce((acc, order) => {
    return acc + order.price * order.quantity;
}, 0);

console.log(myTotalAmount); // 5294

🧠 Practice Examples Using Reduce


βœ… Q1: Find the longest word length

const words = ['apple', 'banana', 'cherry', 'dragonfruit', 'elderberry'];

const longestWordLength = words.reduce((max, word) => {
    return word.length > max ? word.length : max;
}, 0);

console.log(longestWordLength); // 11

βœ… Q2: Find the longest word

const longestWord = words.reduce((longest, word) => {
    return word.length > longest.length ? word : longest;
}, "");

console.log(longestWord); // 'dragonfruit'

βœ… Q3: Find factorial of the largest number

const numbers = [5, 2, 8, 4, 3];

const largestFactorial = numbers.reduce((largest, num) => {
    const currentFactorial = Array
        .from({ length: num })
        .map((_, i) => i + 1)
        .reduce((fact, val) => fact * val, 1);

    return currentFactorial > largest ? currentFactorial : largest;
}, 1);

console.log(largestFactorial); // 40320 (8!)

βœ… Q4: Average score of students scoring above 90

const students = [
    { name: 'John', score: 85 },
    { name: 'Sarah', score: 92 },
    { name: 'Michael', score: 88 },
    { name: 'Emma', score: 95 },
    { name: 'Daniel', score: 90 },
];

const above90StudentsAverage = students
    .filter(student => student.score > 90)
    .reduce((acc, student, i, arr) => acc + student.score / arr.length, 0);

console.log(above90StudentsAverage); // 93.5

πŸ“ Practice Questions

Q5: Filter out books published before 2000 and return titles

const books = [
    { title: 'Book 1', year: 1998 },
    { title: 'Book 2', year: 2003 },
    { title: 'Book 3', year: 1995 },
    { title: 'Book 4', year: 2001 },
];

// Expected Output: ['Book 2', 'Book 4']

Q6: Capitalize the first letter of each word

const strings = ['hello world', 'i am openai', 'welcome to javascript'];

// Expected Output:
// ['Hello World', 'I Am Openai', 'Welcome To Javascript']

🎯 Final Thoughts

Understanding map, filter, and reduce helps you write cleaner and more efficient JavaScript code.
Building their polyfills gives you deeper insight into how these powerful methods work internally.

If you're preparing for interviews, JavaScript mastery, or frontend development, this topic is a must-learn.πŸ”₯