What Does the jQuery $.map() Function Do?
The jQuery $.map() utility function translates all items
in an array or object into a new array by passing each element through a
specified callback function. This article explains how
$.map() works, its syntax, how it handles item
transformation, filtering, and flattening, and how it differs from
standard iteration methods.
Syntax and Parameters
The basic syntax for $.map() is:
$.map(collection, callback(element, indexOrKey))collection: The array or plain JavaScript object you want to iterate over.callback: The function to execute on each item.- The first argument is the current
element(value). - The second argument is the
index(for arrays) orkey(for objects).
- The first argument is the current
The method returns a newly created array containing the transformed values; it does not modify the original collection.
Key Capabilities of
$.map()
Unlike a basic loop, $.map() offers specific behaviors
based on the return value of its callback:
- Value Transformation: Returning a new value places that value in the resulting array.
- Filtering (Removing Items): Returning
nullorundefinedremoves the item entirely from the resulting array, making$.map()useful for both mapping and filtering in a single pass. - Array Flattening: If the callback returns an array, the returned array's elements are flattened into the final result rather than creating a nested array.
Practical Example
const numbers = [1, 2, 3, 4, 5];
const result = $.map(numbers, function(val, index) {
if (val % 2 === 0) {
// Return null to exclude even numbers
return null;
}
// Return the odd number doubled
return val * 2;
});
// result is [2, 6, 10]Differences
from $.each() and Native
Array.prototype.map()
- Versus
$.each():$.each()is an iterator meant for executing side effects and returns the original object unchanged. Its callback parameter order is(index, element). In contrast,$.map()constructs and returns a new transformed array, and its callback order is(element, index). - Versus Native
Array.prototype.map(): Native JavaScriptmap()keeps the array's original length (returningundefinedleavesundefinedin that slot) and only operates on native arrays. jQuery's$.map()can iterate over plain objects, automatically strips outnullandundefined, and flattens returned arrays.