let arr = [A, B, C, [D, E, F, [G, H, I]]];
I've tried many array methods but eventually I didn't get expected result.
I need output like this
let arr = [A, B, C, D, E, F, G, H, I];
Asked
Active
Viewed 80 times
0

Rahul Vanave
- 13
- 4
-
2`let flat = arr.flat(2)` – symlink Jan 14 '20 at 07:39
-
or `arr.flat(Infinity)` if you don't know the depth beforehand – adiga Jan 14 '20 at 08:05
2 Answers
1
You can do it like this,
const arrays = ["A", "B", "C", ["D", "E", "F", ["G","H", "I"]]];
const merge3 = arrays.flat(2); //The depth level specifying how deep a nested array structure should be flattened. Defaults to 1.
console.log(merge3);

Channa
- 3,267
- 7
- 41
- 67
0
For flatten an n-dimensional array using reduce and concat
function flatArray(arr) {
return arr.reduce(function (flat, toFlatten) {
return flat.concat(Array.isArray(toFlatten) ? flatArray(toFlatten) : toFlatten);
}, []);
}
console.log(flatArray(['A', 'B', 'C', ['D', 'E', 'F', ['G', 'H', 'I']]]));

Kapil Tiwari
- 334
- 2
- 7