How to flatten array in jQuery?

extern.fx picture extern.fx · Oct 24, 2011 · Viewed 21.2k times · Source

How to simply flatten array in jQuery? I have:

[1, 2, [3, 4], [5, 6], 7]

And I want:

[1, 2, 3, 4, 5, 6, 7]

Answer

MarioRicalde picture MarioRicalde · Oct 24, 2011

You can use jQuery.map, which is the way to go if you have the jQuery Library already loaded.

$.map( [1, 2, [3, 4], [5, 6], 7], function(n){
   return n;
});

Returns

[1, 2, 3, 4, 5, 6, 7]