jQuery map() Method

The map() method transforms a set of elements or array items into a new array by running a function on each one. Unlike each() which loops and performs side effects, map() collects and returns a transformed value from each iteration.

Two Forms of map()

// Form 1: Instance method — transforms matched elements
$(selector).map(function(index, element) {
    return transformedValue;
});

// Form 2: Static utility — transforms an array
$.map(array, function(value, index) {
    return transformedValue;
});

each() vs map() — The Core Difference

Featureeach()map()
ReturnsOriginal jQuery objectNew jQuery object or array
Use forPerforming actions (side effects)Collecting/transforming values
OutputNothing new collectedNew array of return values

Diagram: each() vs map() Behaviour

  Input: [Apple, Banana, Cherry]

  each():
  → runs function on Apple   → does something (e.g. shows alert)
  → runs function on Banana  → does something
  → runs function on Cherry  → does something
  → returns original set (no new data)

  map():
  → runs function on Apple   → returns "APPLE"
  → runs function on Banana  → returns "BANANA"
  → runs function on Cherry  → returns "CHERRY"
  → returns new array: ["APPLE", "BANANA", "CHERRY"]

Basic map() Example — Collect Text

$(document).ready(function() {
    var names = $("li").map(function() {
        return $(this).text();
    }).get();   // .get() converts jQuery object to plain JS array

    console.log(names);   // ["Apple", "Banana", "Cherry"]
});

The .get() Method After map()

map() returns a jQuery object. Call .get() on it to convert it into a regular JavaScript array you can use anywhere.

var values = $("input[type='checkbox']:checked").map(function() {
    return $(this).val();
}).get();

console.log(values);   // ["option1", "option3"]  (checked ones only)

$.map() — Transform a Plain Array

var numbers = [1, 2, 3, 4, 5];

var doubled = $.map(numbers, function(value) {
    return value * 2;
});

console.log(doubled);   // [2, 4, 6, 8, 10]

$.map() — Filter and Transform Together

Return null or undefined from a $.map() callback to exclude that item from the result.

var scores = [45, 72, 38, 91, 55, 29];

// Get only passing scores (above 50), doubled as bonus display
var bonusScores = $.map(scores, function(score) {
    if (score >= 50) {
        return score;   // include it
    }
    return null;        // exclude failing scores
});

console.log(bonusScores);   // [72, 91, 55]

Diagram: Filtering with $.map()

  Input:  [45, 72, 38, 91, 55, 29]
  Rule:   keep only values >= 50

  45  → < 50 → return null  → excluded
  72  → >= 50 → return 72   → kept
  38  → < 50 → return null  → excluded
  91  → >= 50 → return 91   → kept
  55  → >= 50 → return 55   → kept
  29  → < 50 → return null  → excluded

  Output: [72, 91, 55]

Practical: Collect Form Input Values

$(document).ready(function() {
    $("#gatherBtn").click(function() {
        var allValues = $("input[type='text']").map(function() {
            return $(this).val().trim();
        }).get().filter(function(v) { return v !== ""; });

        console.log("Filled inputs:", allValues);
        $("#output").text(allValues.join(", "));
    });
});

Practical: Transform Table Data

$(document).ready(function() {
    // Get all prices from a table, convert to numbers, sum them
    var prices = $("td.price").map(function() {
        return parseFloat($(this).text().replace("₹", ""));
    }).get();

    var total = prices.reduce(function(sum, val) { return sum + val; }, 0);
    $("#totalPrice").text("Total: ₹" + total.toFixed(2));
});

$.map() on an Object

var person = { first: "Ravi", last: "Kumar", city: "Delhi" };

var values = $.map(person, function(value, key) {
    return key + "=" + value;
});

console.log(values);   // ["first=Ravi", "last=Kumar", "city=Delhi"]

Quick Summary

  • $(selector).map(fn) transforms matched elements into a new jQuery object; use .get() for a plain array.
  • $.map(array, fn) transforms a plain JS array or object into a new array.
  • The key difference from each(): map() collects return values into a new collection.
  • Return null inside $.map() to exclude an item from the result.
  • Use map() when you need a new list of transformed values, not just to loop.

Leave a Comment

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