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"];
1// Although this now may be an older version of how to faltten an
2// array of arrays. I still want to post it so some may have an understanding
3// of how it works
4
5function falltenArray(arr) {
6
7 let result = [...arr];
8 let flattened = false;
9 let counter = 0;
10
11 while (flattened === false){
12 // checks to see if the element at the counter index is an array
13 if (Array.isArray(result[counter])){
14 // unpacks the current array element back into the array
15 result.splice(counter, 1, ...result[counter]);
16 // if so the counter should start at the beginning of the array
17 counter = 0;
18
19 } else {
20 counter += 1;
21 }
22
23 if (counter === result.length){
24 flattened = true;
25 }
26 }
27
28 return result;
29}
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
1function flatten(arr) {
2 return arr.reduce(function (flat, toFlatten) {
3 return flat.concat(Array.isArray(toFlatten) ? flatten(toFlatten) : toFlatten);
4 }, []);
5}
6