0

I was surprised to find that the $.map function of jQuery is defined to:

.. returned array will be flattened into the resulting array.

What should I do if I don't want that behavior, but rather to get an array-of-arrays as the product?

Likely, I will resort to $.each.

Here's code to show what I expected (coming from Scala, where map and flatMap are separate.

var arr= [1,2,3];
var brr= $.map( arr, function(el) {
  return [-el, Math.log(el)];
} );

// 'brr' is:   [-1, 0, -2, 0.6931471805599453, -3, 1.0986122886681098]
// I expected: [[-1, 0], [-2, 0.6931471805599453], [-3, 1.0986122886681098]] 
akauppi
  • 17,018
  • 15
  • 95
  • 120

2 Answers2

2

Just wrap your return value in another array.

return [[-el, Math.log(el)]];
Sean
  • 29,130
  • 4
  • 80
  • 105
  • Cool and wicked! But the intention is not so clear (readability of code) so I'll go with the ECMA map instead. +1 tho – akauppi Sep 30 '14 at 18:28
1

You can simply use native map method of arrays:

var brr = arr.map(function(el) {
  return [-el, Math.log(el)];
});
6502
  • 112,025
  • 15
  • 165
  • 265
  • Thanks, noticed the same in this answer: http://stackoverflow.com/questions/10865025/merge-flatten-an-array-of-arrays-in-javascript The fact that jQuery and ECMAscript 5 do this differently enforces my feeling that jQuery has it "wrong". But anyhow, got a way out now! – akauppi Sep 30 '14 at 18:28
  • @akauppi: warning: thinking that javascript got it right may be true in this very specific case but it's very wrong in many other cases. For example `x && x==false` may be true: we're not in the pure madness of PHP, but not very far either. – 6502 Sep 30 '14 at 18:36
  • True, but out of scope of this Q&A. One of my favourite programming books (because it's short): JavaScript, The Good Parts http://shop.oreilly.com/product/9780596517748.do – akauppi Oct 01 '14 at 20:24