Returning An Array From jQuery's Map() Utility Function

Posted September 16, 2009 at 8:37 AM by Ben Nadel

Tags: Javascript / DHTML

Yesterday, when I was building my jQuery selector step-debugger plugin, I was having some trouble with the jQuery map() utility method. I was trying to map (translate) one array into another, in which the resultant array value was, itself, an array; I thought this would simply insert the return array value as a single index in the mapped array creating an array of arrays. This, however, did not quite work.

To demonstrate what was happening, I put together this small example in which I am going to map an array of names into an array of arrays in which each top-level index contains an array of characters (present in the original name):

  • <script type="text/javascript">
  •  
  • // Create an array of names.
  • var girls = [ "Molly", "Libby" ];
  •  
  • // Now, let's map the above array into an array of arrays
  • // in which each resultant index has an array of letters
  • // from the original word.
  • //
  • // We are going to use the jQuery map() method to translate
  • // the girls array into the expleded girls array. The
  • // function we define below will be executed on each index
  • // of our girls array.
  • var explodedGirls = $.map(
  • girls,
  • function( girlName, girlIndex ){
  •  
  • // Return the girl name split into characters.
  • // "Molly" ==> [ "M","o","l","l","y" ].
  • return( girlName.split( "" ) );
  • }
  • );
  •  
  • // Dump out the newly mapped array to the console.
  • console.log( explodedGirls );
  •  
  • </script>

As you can see, the anonymous function that I am passing to the jQuery map() method simply takes the current name and splits it (explodes) into an array of characters. This character array is then returned as the new mapped index value. When we run this, however, here is what FireBug's console shows us:

["M", "o", "l", "l", "y", "L", "i", "b", "b", "y"]

As you can see, each character array index was individually merged into the mapped array.

As it turns out, this is the natural behavior of the jQuery map() method (as defined in the documentation). And, if we stop to think about it - it makes perfect sense; if we are mapping one array to another, we need a way in which to have the resultant, mapped array be a different length than the original array. Not allowing this would make too many assumptions about the translation that is taking place. And so, to provide this flexibility, returning null from the mapping method deletes the current index value from the mapped array; and, returning an array from the mapping method appends multiple values to the mapped array.

This is very cool, and super useful; but, the question remains: how can I translate a simple value into an array value without it getting flattened into the mapped array? The solution is actually quite simple - you have to package the return array value as an array-of-arrays. This way, the value that gets returned from the mapping method is a one-dimensional array in which the first/only index contains your value array:

  • <script type="text/javascript">
  •  
  • // Create an array of names.
  • var girls = [ "Molly", "Libby" ];
  •  
  • // Now, let's map the above array into an array of arrays
  • // in which each resultant index has an array of letters
  • // from the original word.
  • //
  • // We are going to use the jQuery map() method to translate
  • // the girls array into the expleded girls array. The
  • // function we define below will be executed on each index
  • // of our girls array.
  • var explodedGirls = $.map(
  • girls,
  • function( girlName, girlIndex ){
  •  
  • // Return the girl name split into characters.
  • // "Molly" ==> [ "M","o","l","l","y" ].
  • //
  • // Because the map() function will flatten arrays
  • // into the resultant mapped array, we need to wrap
  • // our results in an array literal so that when jQuery
  • // flattens it, it will only flatten the top-level
  • // array, leaving our exploded-name array intact.
  • return( [ girlName.split( "" ) ] );
  • }
  • );
  •  
  • // Dump out the newly mapped array to the console.
  • console.log( explodedGirls );
  •  
  • </script>

As you can see, I am wrapping my exploded-name array in an array literal. Because jQuery's map() method merges each top-level array value returned from the mapping method, having our exploded name array as a second-level value allows it to remain intact. And, running the above code, FireBug's console shows us:

[ ["M", "o", "l", "l", "y"], ["L", "i", "b", "b", "y"] ]

As you can see, each exploded-name character array is now a single index in the resultant, mapped array. This is a minor caveat, but an important one to understand. Not understanding it yesterday was certainly making my life harder than it needed to be.




Reader Comments

Sep 16, 2009 at 10:30 AM // reply »
29 Comments

Yo dawg I heard you like arrays, so we put arrays in your array so you can reference while you reference :)
(sorry couldn't resist)

But seriously, I think that's quite useful. Thanks for this post!


Sep 17, 2009 at 1:24 PM // reply »
10,640 Comments

@Martin,

Ha ha, thanks.


Post A Comment

Comment Etiquette: Please do not post spam. Please keep the comments on-topic. Please do not post unrelated questions or large chunks of code. And, above all, please be nice to each other - we're trying to have a good conversation here.

Please review the following issues:

Author Name:


Author Email:

Author Website:

Comment:

Supported HTML tags for formatting: <strong>bold</strong>   <em>italic</em>   <code>code</code>







  • Help Wanted - Find Your Next ColdFusion Job
InVision App - Prototyping Made Beautiful With Prototyping Tools Ben Nadel's Company - Epicenter Consulting Recent Blog Comments
Feb 12, 2012 at 3:37 AM
Learning ColdFusion 8: CFImage Part III - Watermarks And Transparency
Hi Ben, Just to ask currently it is placed bottom right corner, if i need to replace the same rendered image on the bottom left side or in the bottom center, how that can be calculated. bottom ce ... read »
Feb 11, 2012 at 9:29 PM
Use jQuery's SlideDown() With Fixed-Width Elements To Prevent Jumping
I can't say how glad I am that I found your post. Thank you very much. ... read »
Feb 10, 2012 at 7:21 PM
jQuery AJAX Strips Script Tags And Inserts Them After Parent-Most Elements
Update! Instead of $(eval(options.insertAfter)).after(data['insertData']); I now use: var ajaxNode = document.createElement('span'); var parent = $(eval(options.insertAfter))[0].parentNode; ... read »
Feb 10, 2012 at 6:18 PM
jQuery AJAX Strips Script Tags And Inserts Them After Parent-Most Elements
encountered this same, what I consider, jQuery bug last week. I'm building a site in which I load some content via AJAX. This content contains Linkedin share button placeholders which Linkedin API ne ... read »
Feb 10, 2012 at 11:30 AM
Cross-Origin Resource Sharing (CORS) AJAX Requests Between jQuery And Node.js
After you understand the concepts here, this is an awesome cheatsheet for enabling CORS in just about anything http://enable-cors.org/ ... read »
JM
Feb 10, 2012 at 9:10 AM
My Safari Browser SQLite Database Hello World Example
@Amy, Here is a very good tutorial on how to use JOIN: http://www.sqltutorial.org/sqljoin-innerjoin.aspx ... read »
Feb 10, 2012 at 4:42 AM
Building A Twitter-Inspired RESTful API Architecture In ColdFusion
This is great, very useful Ben. I spotted a small typo in the api.cgm listing: <cfthrow type="Unauthroized" /> Cheers Stefan ... read »
Feb 9, 2012 at 10:35 PM
CFDirectory Filtering Uses Pipe Character For Multiple Filters (Thanks Steve Withington)
I was wondering if there would be a filter you could apply so that you got everything but what you included in the filter. As in show me all docs that are not a .pdf. ... read »