jQuery map function to perform action on each item of javascript arrays

To perform action on each item of array in javascript requires for loop. That means you have to iterate every item of array by using for loop.

 

Instead of that jQuery provide us simple function called map(), where you can process each item of array without using for loop.

 

map() function syntax:

                                     $.map("your array","callbackfunction")

 

The "callbackfunction" requires two arguments. First argument is the item of the array and second argument is the index in the array. The map() function returns the another array.

 

In the below code, you can find how to use map() function.


<html>
    <head>
        <title>javascript arrays using jQuery map() function</title>
        <script type="text/javascript" src="jquery.js"></script>
        <script type="text/javascript">
            $(document).ready(function() {
                var elems = ['Asp.Net', 'Vb.Net', 'C#.Net', 'Asp.Net MVC', 'Sharepoint']
                elems = $.map(elems, function(n, i) {return (i + 1 + "." + n); });
                $('#divmap').html(elems.join("<br/>"));
            });   
        </script>
    </head>
    <body>
      <p>Array Elements using map() jQuery function</p>
      <div id="divmap"></div>
    </body>
</html>


In the above code we have a array "elems" which has some items.

$.map(elems, function(n, i) {return (i + 1 + "." + n); }) will produce the another array by assigning numbers to the each element in the array "elems".

After indexing each item in the array, we are joining the items by using "<br/>" as separator and assigning to the <div> tag whose id is "divmap" as html.

 

Download source code: jQuery_map.zip (35.69 kb)