SyntaxStudy
Sign Up
jQuery jQuery .map() and Transforming Sets
jQuery Intermediate 5 min read

jQuery .map() and Transforming Sets

.map() transforms a jQuery collection into a new jQuery object by applying a callback to each element and collecting the returned values. It is the jQuery equivalent of JavaScript's Array.prototype.map(), but operates on DOM elements and returns a jQuery object that you can further manipulate or convert to a plain array.

Extracting Data

The most common use of .map() is extracting a property or data value from each element in a set — for example, collecting all input values, all data-id attributes, or all text contents into an array.

Converting to Array

Chain .get() (or .toArray()) after .map() to convert the resulting jQuery object to a plain JavaScript array, ready for use with standard array methods like Array.join() or JSON.stringify().

  • Callback signature: function(index, element)
  • Return null or undefined to exclude an item from the result
  • Chain .get() to get a plain array
  • $.map(array, fn) — utility version for plain arrays

Use $.map() (the utility version) when transforming a plain JavaScript array or object rather than a jQuery set — it avoids the overhead of creating a jQuery object.

Example
// Collect all input values into an array
var values = $('#survey input[type="text"]').map(function () {
    return $(this).val();
}).get();
console.log('Values:', values);

// Collect data-id attributes
var ids = $('.product-card').map(function () {
    return $(this).data('id');
}).get();
console.log('Product IDs:', ids.join(', '));

// Filter while mapping — return null to skip
var nonEmpty = $('input[type="text"]').map(function () {
    var v = $(this).val().trim();
    return v !== '' ? v : null;
}).get();

// $.map on a plain array
var doubled = $.map([1, 2, 3, 4], function (n) {
    return n * 2;
});
console.log(doubled); // [2, 4, 6, 8]
Pro Tip

Return null inside .map() to exclude an element from the result — useful for filtering and transforming in one pass.