Tuesday, May 1, 2012

How to flatten array in jQuery?


How to simply flatten array in jQuery? I have: [1, 2, [3, 4], [5, 6], 7] And want: [1, 2, 3, 4, 5, 6, 7]



Source: Tips4all

4 comments:

  1. 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]

    ReplyDelete
  2. 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]

    ReplyDelete
  3. 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.

    ReplyDelete
  4. You can use jQuery.map():


    callback( value, indexOrKey )The function to process each item
    against. The first argument to the function is the value; the second
    argument is the index or key of the array or object property. The
    function can return any value to add to the array. A returned array
    will be flattened into the resulting array. Within the function, this
    refers to the global (window) object.

    ReplyDelete