Ben Nadel
On User Experience (UX) Design, JavaScript, ColdFusion, Node.js, Life, and Love.
I am the chief technical officer at InVision App, Inc - a prototyping and collaboration platform for designers, built by designers. I also rock out in JavaScript and ColdFusion 24x7.
Meanwhile on Twitter
Loading latest tweet...
Ben Nadel at cf.Objective() 2013 (Bloomington, MN) with:

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

By Ben Nadel on

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

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!

Reply to this Comment

Thank you very much Ben for this post. I was on this exact same issue (trying to return an array into a mapped array instead of individually merged values). And I had figured the [ ] but without the enclosing ( ) (in the expression equivalent to return( [ girlName.split( "" ) ] ); )
And it was wasting my time until I got here, so thank you!

Reply to this Comment

Post A Comment

You — Get Out Of My Dreams, Get Into My Comments
Live in the Now
Oops!
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.