How to flatten array in jQuery?
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]
Use the power of JavaScript:
var a = [[1, 2], 3, [4, 5]];
console.log( Array.prototype.concat.apply([], a) );
//will output [1, 2, 3, 4, 5]
var a = [1, 2, [3, 4], [5, [6, [7, 8]]]];
var b = [];
function flatten(e,b){
if(typeof e.length != "undefined")
{
for (var i=0;i<e.length;i++)
{
flatten(e[i],b);
}
}
else
{
b.push(e);
}
}
flatten(a,b);
console.log(b);
The flatten function should do it, and this doesn't require jQuery. Just copy all of this into Firebug and run it.
Here's how you could use jquery to flatten deeply nested arrays:
$.map([1, 2, [3, 4], [5, [6, [7, 8]]]], function recurs(n) {
return ($.isArray(n) ? $.map(n, recurs): n);
});
Returns:
[1, 2, 3, 4, 5, 6, 7, 8]
Takes advantage of jQuery.map as well as jQuery.isArray.