Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to flatten array in jQuery?

People also ask

Why would you flatten an array?

Flattening an array is a process of reducing the dimensionality of an array. In other words, it a process of reducing the number of dimensions of an array to a lower number.

What is flatten method?

Prototype - flatten() Method This method returns a flat (one-dimensional) version of the array. Nested arrays are recursively injected inline. This can prove very useful when handling the results of a recursive collection algorithm.


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]

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.


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.