Charles W. Charles W. - 4 months ago 19
Javascript Question

Array.map 1 element to multiple element

I have

[3, 16, 120]
. when I do
[3, 16, 120].map(mapper)
, I want to achieve, for example
[4,5, 17,18, 121,122]
i.e. each element map to n+1 and n+2. This is of course an example - what I want is to simply push multiple values from mapper function

Do I have to use Array.each and push to an array, or is it possible to do it with Array.map (or other built-in api)

Answer

Not particularly nice, but it is a possible solution:

var arr = [3, 16, 120];

console.log([].concat.apply([], arr.map(function (n) { return [n+1, n+2]; })));