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]
1const flatten = (ary) => ary.reduce((a, b) => a.concat(Array.isArray(b) ? flatten(b) : b), [])
2
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}
1function flatten(arr) {
2 const result = []
3
4 arr.forEach((i) => {
5 if (Array.isArray(i)) {
6 result.push(...flatten(i))
7 } else {
8 result.push(i)
9 }
10 })
11
12 return result
13}
14
15// Usage
16const nested = [1, 2, 3, [4, 5, [6, 7], 8, 9]]
17
18flatten(nested) // [1, 2, 3, 4, 5, 6, 7, 8, 9]