56

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]
Gibolt
  • 42,564
  • 15
  • 187
  • 127
extern.fx
  • 643
  • 1
  • 5
  • 9

10 Answers10

63

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]
MarioRicalde
  • 9,131
  • 6
  • 40
  • 42
  • 6
    Granted, that is the way it was phrased in the question, but, this too will only flatten one level. – phil Nov 28 '12 at 02:10
  • For those wondering how this works: unlike `Array.prototype.map` jQuery's `map` has special handling for arrays returned from the callback function: _The [callback] function can return any value. A returned array will be flattened into the resulting array_ – Nickolay May 06 '18 at 23:58
35

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]
bjornd
  • 22,397
  • 4
  • 57
  • 73
25

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.

Xavi
  • 20,111
  • 14
  • 72
  • 63
11
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.

dnuttle
  • 3,810
  • 2
  • 19
  • 19
  • I should add that this will flatten not only arrays, but anything that has a "length" method. It is not really possible to be sure in Javascript that something is a true array unless it was declared as new Array(). – dnuttle Oct 24 '11 at 12:03
  • dnuttle: Actually, I think using `obj instanceof Array` is pretty much granted to work. (Unless if there's another variable named Array, then you can use `obj instanceof [].constructor`) –  Oct 24 '11 at 17:58
  • Hmm. You're right. I could have sworn I'd tried that before and it didn't work. – dnuttle Oct 24 '11 at 23:08
  • dnuttle: This answer discusses it: http://stackoverflow.com/questions/1058427/how-to-detect-if-a-variable-is-an-array/1058753#1058753 It seems there are problems with my method :( –  Oct 25 '11 at 21:06
  • You could always use `$.isArray`. Pure js is great, but libraries are nice too =]. – Xavi Oct 08 '12 at 08:28
  • Upvote as your solution is clear as to what is going on. Other answers using $.map or Array.prototype.concat.apply([], arr) are very clever, but if anyone else views the code may have no idea what is going on. – Jai Apr 01 '14 at 01:45
5

To recursively flatten an array you can use the native Array.reduce function. The is no need to use jQuery for that.

function flatten(arr) {
    return arr.reduce(function flatten(res, a) { 
        Array.isArray(a) ? a.reduce(flatten, res) : res.push(a);
        return res;
    }, []);
}

Executing

flatten([1, 2, [3, 4, [5, 6]]])

returns

[ 1, 2, 3, 4, 5, 6 ]
Fabian Jakobs
  • 28,815
  • 8
  • 42
  • 39
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.

Sarfraz
  • 377,238
  • 77
  • 533
  • 578
1

Use recursion if you have multiple levels:

flaten = function(flatened, arr) {
    for(var i=0;i<arr.length;i++) {
        if (typeof arr[i]!="object") {
            flatened.push(arr[i]);
        }
        else {
            flaten(flatened,arr[i]);
        }
    }
    return;
}

a=[1,[4,2],[2,7,[6,4]],3];
b=[];
flaten(b,a);
console.log(b);
Mr Boss
  • 739
  • 2
  • 8
  • 17
1

You can use Array.prototype.reduce which is technically not jQuery, but valid ES5:

var multidimensionArray = [1, 2, [3, 4], [5, 6], 7];
var initialValue = [];

var flattened = multidimensionArray.reduce(function(accumulator, current) {
    return accumulator.concat(current);
}, initialValue);

console.log(flattened);
Elise Chant
  • 5,048
  • 3
  • 29
  • 36
0

Old question, I know, but...

I found this works, and is fast:

function flatten (arr) {
  b = Array.prototype.concat.apply([], arr);
  if (b.length != arr.length) {
    b = flatten(b);
  };

  return b;
}
phil
  • 4,668
  • 4
  • 33
  • 51
0

You need arr.flat([depth])

var arr1 = [1, 2, [3, 4]];
arr1.flat(); 
// [1, 2, 3, 4]

var arr2 = [1, 2, [3, 4, [5, 6]]];
arr2.flat();
// [1, 2, 3, 4, [5, 6]]

var arr3 = [1, 2, [3, 4, [5, 6]]];
arr3.flat(2);
// [1, 2, 3, 4, 5, 6]
Eugen Konkov
  • 22,193
  • 17
  • 108
  • 158