views:

432

answers:

2

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.

+2  A: 

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
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
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
Could you maybe use arrays of objects, like [{a,b},{c,d},{e,f}] and have your callback function also return an object?
evilpenguin
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
A: 

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]]

Hope that helps!

T.J. VanSlyke