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

Posted September 16, 2009 at 8:37 AM

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):

 Launch code in new window » Download code as text file »

  • <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:

 Launch code in new window » Download code as text file »

  • <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.

Download Code Snippet ZIP File

Post Comment  |  Ask Ben  |  Permalink  |  Other Searches  |  Print Page




Reader Comments

Sep 16, 2009 at 10:30 AM // reply »
18 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 »
6,516 Comments

@Martin,

Ha ha, thanks.


Post Comment  |  Ask Ben

Recent Blog Comments
Nov 22, 2009 at 1:56 AM
Learning ColdFusion 9: Using CFQuery In CFScript Can Enable SQL Injection Attacks
Why adobe would give you script equivalent of cfquery is beyond me. I love cfquery tag because it helps me wriite clean sql, and get away from the horrible jdbc queries If I wanted to write javali ... read »
Nov 22, 2009 at 1:45 AM
Streaming Text Using ColdFusion's CFContent Tag And The Variable Attribute
The reason you would want to do this is to stream. Ack json/xml files to ria clients I used thus technique before because putting json in response stream causes debugging info to come thru As well a ... read »
Nov 21, 2009 at 6:47 PM
Hal Helms - Real World Object Oriented Development, Sarasota - Day Five
@charlie griefer, Thank you.. ... read »
Nov 21, 2009 at 5:15 PM
Using ColdFusion Structures To Remove Duplicate List Values
@Jose Galdamez, Oh heh yeah I didn't paste the whole code. I should have defined the vars -- my bad. It's fixed thou. Thanks. ... read »
Nov 21, 2009 at 4:49 PM
Styling The ColdFusion 8 WriteToBrowser CFImage Output
Great work yet again Ben! Whilst I didn't use this whole code, I copied some of your regex code for a similar problem with the lack of an alt attribute and unescaped ampersands in CFIMAGE for Railo 3 ... read »
Nov 21, 2009 at 1:13 PM
My First ColdFusion Builder Extension - Encrypting And Decrypting CFM / CFC Files
@Ben, Because I am pedantic, I just want to make sure that everyone knows there is absolutely no encryption going on. There is only encoding and obfuscation. The cfencode tool only obfuscates your C ... read »
Nov 21, 2009 at 12:28 PM
Using ColdFusion Structures To Remove Duplicate List Values
@Jody I can't seem to get your code sample to work. If you are still having problems, try this code out and see if it gets you what you wanted. <!--- Comma delimited list with various duplicates ... read »
Nov 21, 2009 at 11:03 AM
Groovy Operator Overloading Does Not Work In The ColdFusion Context
Hi Ben, Thanks for this informative post. Now I am reading ur old posts too ... read »