HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

jQuery map() Method

The map() method is used to transform one array or jQuery object into a **new array**. While each() is used for action, map() is used for **extraction and transformation**.


1. The $.map() Utility

This version is used for plain JavaScript arrays or objects. It takes the data and a callback function that defines what the new values should be.

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

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

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

2. The .map() Selector Method

This version is used on a jQuery selection. It is excellent for extracting specific attributes or text from a list of elements into a clean array.

var ids = $("input").map(function() {
    return $(this).attr("id");
}).get(); // use .get() to turn the jQuery object into a real Array

// Result: ["name", "email", "password"]
console.log(ids);
Important: When using .map() on a selector, you must call .get() at the end if you want a basic JavaScript array.

Removing Items with map()

You can remove items from the resulting array by returning null inside the callback function. This effectively filters and maps at the same time.

var items = [10, 50, 5, 100];

var bigItems = $.map(items, function(val) {
    return (val > 20) ? val : null; // Only keep items greater than 20
});

// Result: [50, 100]
map() vs each():
  • each() returns the original collection (used for doing things).
  • map() returns a NEW collection (used for getting data).

Practical Use Case: Tag List

If you have a group of checkboxes and want to get a comma-separated string of the labels of all checked items.

$("#btn").click(function() {
    var selectedTags = $("input:checked").map(function() {
        return $(this).val();
    }).get().join(", ");
    
    $("#result").text("Selected: " + selectedTags);
});

Key Points to Remember

  • map() always returns a new array or collection.
  • $.map() works on arrays; .map() works on DOM elements.
  • Use .get() after DOM mapping to convert it to a standard JavaScript array.
  • Return null to exclude an item from the new array.
  • It is the backbone of data extraction in modern jQuery applications.