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 »
11,246 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
Ben Nadel's Company - Epicenter Consulting Recent Blog Comments
May 25, 2013 at 10:01 PM
My Experience With AngularJS - The Super-heroic JavaScript MVW Framework
@Avi, Really glad to help! @Jaredwilli, I'm finding a this image hits home with a lot of people :) Hopefully we can all work through the rough patches together! @Prateek, AngularJS has error ... read »
May 25, 2013 at 9:53 PM
Nested Views, Routing, And Deep Linking With AngularJS
@Mrsean2k, I'm glad I could help! I haven't been able to keep up with the ui-router stuff. I keep saying that I'll carve out time, but I just haven't gotten to it :( ... read »
May 25, 2013 at 9:49 PM
What If All User Interface (UI) Data Came In Reports?
@Jonah, Thanks for the book recommendations. I am looking them up right now. I can see that Object Thinking is available for the Kindle App - sweet! Also, I just recently heard Martin Fowler on the ... read »
May 25, 2013 at 9:41 PM
HashKeyCopier - An AngularJS Utility Class For Merging Cached And Live Data
@Chris, I'm super excited to hear that my posts are helpful. I am also loving AngularJS; but, it definitely has some caveats and some odd behaviors and some things that just don't seem to "wor ... read »
May 25, 2013 at 9:36 PM
Ask Ben: Manually Enforcing Basic HTTP Authorization In ColdFusion
@Adam, @Jason, After reading these comments, I double-checked my latest implementation and I am happy to report that I am using listFirst() and listRest(). ... read »
May 25, 2013 at 9:31 PM
Using "//" And ".//" Expressions In XPath XML Search Directives In ColdFusion
@Daxesh, I am not sure I understand the question about the current node. If you already have a reference to the current node, why would you need to query for it? As for parent node, I believe that ... read »
May 25, 2013 at 10:08 AM
Using "//" And ".//" Expressions In XPath XML Search Directives In ColdFusion
@Ben, my question is that i want the current node with its tag and its parent node. i just want only that data. So, give me the solution for that. and remember solution is working on " xpath 1.0 ... read »
May 25, 2013 at 10:01 AM
Using "//" And ".//" Expressions In XPath XML Search Directives In ColdFusion
hey ben, i want get my current node tag and also want the root node tag withing. So, how can i fix it.. ! ... read »
InVision App - Prototyping Made Beautiful With Prototyping Tools