# An array of arrays can be merged or flattened.

## Problem

I have a JavaScript array that looks like this:

``````[["\$6"], ["\$12"], ["\$25"], ["\$25"], ["\$18"], ["\$22"], ["\$10"]]
``````

How would I go about combining the several inner arrays into a single one, such as:

``````["\$6", "\$12", "\$25", ...]
``````

## Solution #1

Concat can be used to combine arrays:

Because the apply method of concat only accepts an array as the second parameter, the last line is similar to this:

``````var merged2 = [].concat(["\$6"], ["\$12"], ["\$25"], ["\$25"], ["\$18"], ["\$22"], ["\$10"]);
``````

You could also flatten the arrays with the Array.prototype.flat() method (added in ES2019), albeit it is only available in Node.js starting with version 11, and not at all in Internet Explorer.

## Solution #2

Here’s a little function that flattens an n-dimensional array using some of the newer JavaScript array capabilities.

``````function flatten(arr) {
return arr.reduce(function (flat, toFlatten) {
return flat.concat(Array.isArray(toFlatten) ? flatten(toFlatten) : toFlatten);
}, []);
}
``````

Usage:

``````flatten([[1, 2, 3], [4, 5]]); // [1, 2, 3, 4, 5]
flatten([[[1, [1.1]], 2, 3], [4, 5]]); // [1, 1.1, 2, 3, 4, 5]
``````

## Solution #3

There’s a mysteriously concealed method that creates a new array without changing the original:

## Solution #4

The best way to achieve it is to use the javascript reduction function.

``````var arrays = [["\$6"], ["\$12"], ["\$25"], ["\$25"], ["\$18"], ["\$22"], ["\$10"], ["\$0"], ["\$15"],["\$3"], ["\$75"], ["\$5"], ["\$100"], ["\$7"], ["\$3"], ["\$75"], ["\$5"]];

arrays = arrays.reduce(function(a, b){
return a.concat(b);
}, []);
``````

Or, with ES2015:

``````arrays = arrays.reduce((a, b) => a.concat(b), []);
``````

js-fiddle

Mozilla docs

## Solution #5

To implement this, there’s a new native method called flat.

(As of late 2019, flat is now part of the ECMA 2019 standard, and core-js@3 (babel’s library) has it in their polyfill library.)

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

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

// Flatten 2 levels deep
const arr3 = [2, 2, 5, [5, [5, [6]], 7]];
arr3.flat(2);
// [2, 2, 5, 5, 5, [6], 7];

// Flatten all levels
const arr4 = [2, 2, 5, [5, [5, [6]], 7]];
arr4.flat(Infinity);
// [2, 2, 5, 5, 5, 6, 7];
``````