Flattening bi-dimensional arrays is trivial with Spread operator.
1 2 3 4 | const biDimensionalArr = [11, [22, 33], [44, 55], [66, 77], 88, 99]; // [11, 22, 33, 44, 55, 66, 77, 88, 99] const flattenArr = [].concat(...biDimensionalArr); |
But you can make it work with multi-dimensional arrays by recursive calls,
1 2 3 4 5 6 7 | function flattenMultiArray(arr) { const flattened = [].concat(...arr); return flattened.some(item => Array.isArray(item)) ? flattenMultiArray(flattened) : flattened; } const multiDimensionalArr = [11, [22, 33], [44, [55, 66, [77, [88]], 99]]]; const flatArr = flattenMultiArray(multiDimensionalArr); // [11, 22, 33, 44, 55, 66, 77, 88, 99] |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.