How to flatten array in jQuery?

JavascriptJqueryArraysFlatten

Javascript Problem Overview


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]

Javascript Solutions


Solution 1 - Javascript

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]

Solution 2 - Javascript

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]

Solution 3 - Javascript

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.

Solution 4 - Javascript

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.

Solution 5 - Javascript

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 ]

Solution 6 - Javascript

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.

Solution 7 - Javascript

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);

Solution 8 - Javascript

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);

Solution 9 - Javascript

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;
}

Solution 10 - Javascript

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]

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionextern.fxView Question on Stackoverflow
Solution 1 - JavascriptMarioRicaldeView Answer on Stackoverflow
Solution 2 - JavascriptbjorndView Answer on Stackoverflow
Solution 3 - JavascriptXaviView Answer on Stackoverflow
Solution 4 - JavascriptdnuttleView Answer on Stackoverflow
Solution 5 - JavascriptFabian JakobsView Answer on Stackoverflow
Solution 6 - JavascriptSarfrazView Answer on Stackoverflow
Solution 7 - JavascriptMr BossView Answer on Stackoverflow
Solution 8 - JavascriptElise ChantView Answer on Stackoverflow
Solution 9 - JavascriptphilView Answer on Stackoverflow
Solution 10 - JavascriptEugen KonkovView Answer on Stackoverflow