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,314 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
Jun 19, 2013 at 8:17 AM
My Experience With AngularJS - The Super-heroic JavaScript MVW Framework
@Prateek, to match a word or text you should use .toContain('word') that's a jasmine reference. website is : http://pivotal.github.io/jasmine/ ... read »
Jun 19, 2013 at 8:10 AM
My Experience With AngularJS - The Super-heroic JavaScript MVW Framework
Hi Guys, Actually i am doing e2e test of angular js of my project but i am not getting one thing that is how to press enter key through the test when my form is filled as i am not using a button but ... read »
Jun 18, 2013 at 9:20 PM
Mapping AngularJS Routes Onto URL Parameters And Client-Side Events
I couldn't find examples of passing multiple arguments using the when() routing statement so figured out through trial and error that you can pass multiple arguments using the following format: .whe ... read »
Jun 18, 2013 at 3:39 PM
Experimenting With The Amazon Simple Storage Service (S3) API Using ColdFusion
Hi Ben, THANKS! While not bleeding edge, it is new to me & I like learning new things every day! ... read »
Jun 18, 2013 at 12:30 PM
Disabling Auto-Correct And Auto-Capitalize Features On iPhone Inputs
Also spellcheck="false" should be mentioned as part of html5 specs ... read »
Jun 18, 2013 at 8:40 AM
Using Named Functions Within Self-Executing Function Blocks In Javascript
Hi Ben, you forgot to mention the most important thing for named self-executing functions - they can be referenced by name ONLY inside their execution context (which is parens in this case), it mean ... read »
dee
Jun 18, 2013 at 7:01 AM
My Safari Browser SQLite Database Hello World Example
hai ben, this program is really good i could understand the concept but i dint know how to save it and how to open it as you have done in the video can u give that details pls ... read »
Jun 18, 2013 at 6:04 AM
Clearing Inline CSS Properties With jQuery
Thanks a lot for for post! It helped me a lot... after being stuck since 24 hrs.. found solution from your post. Thanks again! ... read »
InVision App - Prototyping Made Beautiful With Prototyping Tools