jQuery map() example

jQuery map() function is used to translate all items in an array or object to a new array of items.

Example 1

Use $.map() to change the values of an array.
<!doctype html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <title>jQuery.map demo</title>
    <style>
        div {
            color: blue;
        }

        p {
            color: green;
            margin: 0;
        }

        span {
            color: red;
        }
    </style>
    <script src="https://code.jquery.com/jquery-3.4.1.js"></script>
</head>

<body>

    <div></div>
    <p></p>
    <span></span>

    <script>
        var arr = ["a", "b", "c", "d", "e"];
        $("div").text(arr.join(", "));

        arr = jQuery.map(arr, function(n, i) {
            return (n.toUpperCase() + i);
        });
        $("p").text(arr.join(", "));

        arr = jQuery.map(arr, function(a) {
            return a + a;
        });
        $("span").text(arr.join(", "));
    </script>

</body>

</html>
Try it Yourself - Copy paste code in Online HTML Editor to see the result

Example 2

Map the original array to a new one and add 4 to each value.
$.map( [ 0, 1, 2 ], function( n ) {
  return n + 4;
});
Result:
1
[4, 5, 6]

Example 3

Map the original object to a new array and double each value.
var dimensions = { width: 10, height: 15, length: 20 };
dimensions = $.map( dimensions, function( value, index ) {
  return value * 2;
});
Result:
1
[ 20, 30, 40 ]

References


Comments