1// using recursion, .reduce() and .concat() methods
2// works with arrays of any depth
3
4function flatten(arr)
5{
6 return arr.reduce((acc, cur) => acc.concat(Array.isArray(cur) ? flatten(cur) : cur), []);
7};
8
9const arr = [[1,2],[3,[4,[5]]]];
10
11const flattened = flatten(arr);
12console.log(flattened);
13
14/*
15 Output: [ 1, 2, 3, 4, 5 ]
16*/
1// flat(depth),
2// depth is optional: how deep a nested array structure
3// should be flattened.
4// default value of depth is 1
5
6const arr1 = [1, 2, [3, 4]];
7arr1.flat();
8// [1, 2, 3, 4]
9
10const arr2 = [1, 2, [3, 4, [5, 6]]];
11arr2.flat();
12// [1, 2, 3, 4, [5, 6]]
13
14const arr3 = [1, 2, [3, 4, [5, 6]]];
15arr3.flat(2);
16// [1, 2, 3, 4, 5, 6]
17
18const arr4 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]];
19arr4.flat(Infinity);
20// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
1var arrays = [
2 ["$6"],
3 ["$12"],
4 ["$25"],
5 ["$25"],
6 ["$18"],
7 ["$22"],
8 ["$10"]
9];
10var merged = [].concat.apply([], arrays);
11
12console.log(merged);
1var multiDimensionArray = [["a"],["b","c"],["d"]]; //array of arrays
2var flatArray = Array.prototype.concat.apply([], multiDimensionArray); //flatten array of arrays
3console.log(flatArray); // [ "a","b","c","d"];
1const arr = [1, 2, [3, 4]];
2
3// To flat single level array
4arr.flat();
5// is equivalent to
6arr.reduce((acc, val) => acc.concat(val), []);
7// [1, 2, 3, 4]
8
9// or with decomposition syntax
10const flattened = arr => [].concat(...arr);
11