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 flattenArray = function(data) {
2 return data.reduce(function iter(r, a) {
3 if (a === null) {
4 return r;
5 }
6 if (Array.isArray(a)) {
7 return a.reduce(iter, r);
8 }
9 if (typeof a === 'object') {
10 return Object.keys(a).map(k => a[k]).reduce(iter, r);
11 }
12 return r.concat(a);
13 }, []);
14}
15console.log(flattenArray(data))
16
17//replace data with your array
18
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);
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 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]