47

I'm mapping an array of two-tuples from one domain (dates) to another (timestamps). Unfortunately, it looks like jQuery.map auto-flattens the two-tuples I return, and I don't see a do_not_flatten parameter.

Am I missing something else in the library that won't auto-flatten?

Addendum: I assume that I shouldn't be using Array.map, which does not auto-flatten, because it is JavaScript 1.6. As I understand it, jQuery is supposed to abstract away the JavaScript version I'm running for compatibility reasons.

cdleary
  • 69,512
  • 53
  • 163
  • 191

2 Answers2

69

I was having the same problem; it turns out you can just return a nested array from within the $.map callback and it won't flatten the outer array:

$.map([1, 2, 3], function(element, index) {
  return [ element + 1, element + 2 ];
});
=> [2, 3, 3, 4, 4, 5]

Whereas:

$.map([1, 2, 3], function(element, index) {
  return [ [ element + 1, element + 2 ] ];
});
=> [[2, 3], [3, 4], [4, 5]]
starball
  • 20,030
  • 7
  • 43
  • 238
T.J. VanSlyke
  • 699
  • 5
  • 3
  • 11
    Really neat! But seriously, such a hack should't be needed. Thanks anyway! – Fuad Saud Aug 02 '13 at 20:57
  • 5
    Real ugly, the map function should accept a boolean or something to control this behaviour. – monoceres Feb 17 '14 at 12:34
  • 8
    I think the map function shouldn't flatten its result at all. I rarely have any reason to want this behavior. There should be a separate function for situations where someone wants the result to be flattened. – Elias Zamaria Jul 01 '14 at 21:57
  • I wonder about the performance implications. But then again JS is quite fast usually – Steven Lu Oct 26 '14 at 00:58
0

I'm not really sure what a "two-tuple" is and I'm not really sure I got it right from the Google results I looked at. But did you take a look at jQuery.each?

evilpenguin
  • 5,448
  • 6
  • 41
  • 49
  • A two-tuple is a pair of values (x, y). A three-tuple is a set of three values (x, y, z). Sure, I could do it using a loop, but the point of `map` is that you use a single function to map from an input type to an output type. – cdleary Mar 31 '09 at 23:01
  • Maybe I'm out of my league, but "The translation function that is provided to this method is called for each item in the array" seems like a kind of a loop to me.. – evilpenguin Mar 31 '09 at 23:09
  • Could you maybe use arrays of objects, like [{a,b},{c,d},{e,f}] and have your callback function also return an object? – evilpenguin Mar 31 '09 at 23:13
  • You're totally right -- map is equivalent to something like: `new_vals = []; for (old_val in old_vals) { new_vals.push(some_fun(old_val)) }`. Map is a cleaner way of expressing that: `new_vals = map(some_fun, old_vals);` I could use pair objects, like you suggest, but the plot library wants 2-tups. – cdleary Mar 31 '09 at 23:19