# Flatten array JavaScript recursion | Example code

Use concat() and push() method with for loop to get Flatten array in JavaScript recursion. The solution below uses array.concat(…) to combine both the result of the recursion (going down the tree), but also to combine the results of processing the rest of the list (at the same level).

## Flatten array JavaScript recursion

Simple example code when calling `flatten` recursively, you need to pass `arr[i]` to it and then concat the result with newArr.

Flatten nested arrays while preserving the order, e.g. `[[1, 2], 3, [4, [[5]]]]` should be converted to `[1, 2, 3, 4, 5]`.

``````<!DOCTYPE html>
<html>
<body>

<script>
function flatten (arr) {
var newArr = [];
for (var i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i])) {
newArr = newArr.concat(flatten(arr[i]));
} else {
newArr.push(arr[i]);
}
}
return newArr;
}

var res = flatten([[1, 2], 3, [4, [[5]]]]);

console.log(res)
</script>

</body>
</html>
``````

Output:

Here’s a more modern version:

``````function flatten(items) {
const flat = [];

items.forEach(item => {
if (Array.isArray(item)) {
flat.push(...flatten(item));
} else {
flat.push(item);
}
});

return flat;
}``````

#### The clean way to flatten an Array in 2019 with ES6 is `flat()`:

``````const array = [1, 1, [2, 2], [[3, [4], 3], 2]]

// All layers
array.flat(Infinity) // [1, 1, 2, 2, 3, 4, 3, 2]

// Varying depths
array.flat() // [1, 1, 2, 2, Array(3), 2]

array.flat(2) // [1, 1, 2, 2, 3, Array(1), 3, 2]
array.flat().flat() // [1, 1, 2, 2, 3, Array(1), 3, 2]

array.flat(3) // [1, 1, 2, 2, 3, 4, 3, 2]
array.flat().flat().flat() // [1, 1, 2, 2, 3, 4, 3, 2]
``````

Do comment if you have any doubts or suggestions on this JS Array topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

This site uses Akismet to reduce spam. Learn how your comment data is processed.