JavaScript Interview — Flatten an array
1 min readNov 20, 2019
Write a function which takes an array containing either ints or arrays of ints and return a flat array.
Input: [1, [2, [ [3, 4], 5], 6]]
Output: [1, 2, 3, 4, 5, 6]
Method 1: Using inbuilt method “flat”
This is the easiest method to flatten the array as “flat” will recurse until the given depth which in this case is “Infinity” and return the flatten array.
Method 2: Using Array “reduce”
In this method we are using the reduce method, starting the concatenation of the reduce result and calling the method recursively until all the elements are iterated.
Reference: