Access Current Index in jQuery .map() Callback
Accessing the current index in a jQuery .map() callback
depends on whether you are using the jQuery collection method
$(selector).map() or the core utility function
$.map(). While both allow you to access the loop index,
their callback parameter orders are inverted. This guide covers how to
correctly identify and use the index parameter in both variations.
1. Using
$(selector).map() on a jQuery Collection
When iterating over DOM elements using a jQuery selection, the callback function passes the index as the first argument and the DOM element as the second argument.
$('li').map(function(index, element) {
console.log("Current index:", index);
console.log("Current element:", element);
// You can also use 'this' to reference the DOM element
return index + ': ' + $(this).text();
}).get();- First argument (
index): A zero-based integer representing the current position of the element in the set. - Second argument (
element): The raw DOM element (equivalent tothis).
2. Using the Utility Function
$.map()
When using the generic utility method $.map() to
transform standard JavaScript arrays or objects, the argument order is
reversed to mirror native JavaScript patterns. Here, the element
is the first argument and the index is the second
argument.
var items = ['apple', 'banana', 'orange'];
var result = $.map(items, function(element, index) {
console.log("Current index:", index);
console.log("Current element:", element);
return index + '-' + element;
});- First argument (
element): The current item being processed. - Second argument (
index): The zero-based index of the array (or the key name if iterating over an object).
Key Takeaway
To avoid bugs when retrieving the index:
- Use
function(index, element)for$(selector).map(). - Use
function(element, index)for$.map(array, callback).