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**.
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);
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);
.map() on a selector, you must call
.get() at the end if you want a basic JavaScript array.
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]
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);
});