How to flatten an array in JavaScript?

  1. Array.prototype.flat()
  2. reduce + concat + isArray + recursivity
  3. ES3

Array.prototype.flat()

1
2
3
4
5
6
7
8
9
const arr1 = [0, 1, 2, [3, 4]];

console.log(arr1.flat());
// expected output: [0, 1, 2, 3, 4]

const arr2 = [0, 1, 2, [[[3, 4]]]];

console.log(arr2.flat(2));
// expected output: [0, 1, 2, [3, 4]]

reduce + concat + isArray + recursivity

1
2
3
4
5
6
7
8
9
10
const arr = [1, 2, [3, 4, [5, 6]]];

// to enable deep level flatten use recursion with reduce and concat
function flatDeep(arr, d = 1) {
return d > 0 ? arr.reduce((acc, val) => acc.concat(Array.isArray(val) ? flatDeep(val, d - 1) : val), [])
: arr.slice();
};

flatDeep(arr, Infinity);
// [1, 2, 3, 4, 5, 6]

ES3

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
function flat(arr, depth) {
depth = typeof depth === 'number' ? depth : 1;
var flattened = [];
var isArray = function(arg) {
return Object.prototype.toString.call(arg) === '[object Array]';
};
var doFlat = function(arr, depth) {
for (var i = 0; i < arr.length; i++) {
var el = arr[i];
if (isArray(el) && depth > 0) {
doFlat(el, depth - 1);
} else {
flattened.push(el);
}
}
};
doFlat(arr, depth);
return flattened;
}