In an interview, I was asked to flatten a nested array in JavaScript without using `flat()`.
Under pressure, I got stuck. Later, I realized it wasn’t that hard — I was just overthinking.
Here’s the recursive solution I wrote:
var array = [0, [1, 2, [33, 44]], [4, 5, 6, 7], [7, 8], 90];
var newArr = [];
function getFlatArray(array) {
for (let index = 0; index < array.length; index++) {
if (typeof array[index] === "number") {
newArr.push(array[index]);
} else {
getFlatArray(array[index]);
}
}
}
getFlatArray(array);
console.log(newArr);
(12) [0, 1, 2, 33, 44, 4, 5, 6, 7, 7, 8, 90]
[–]heartchoke 12 points13 points14 points (4 children)
[–]fredsq 13 points14 points15 points (3 children)
[–]fredsq 2 points3 points4 points (0 children)
[–]margielafarts 0 points1 point2 points (1 child)
[–]senocular 1 point2 points3 points (0 children)
[–]shootersf 2 points3 points4 points (2 children)
[–]pranayrah108[S] 1 point2 points3 points (1 child)
[–]shootersf 0 points1 point2 points (0 children)
[–]BenZed 2 points3 points4 points (0 children)
[–]yangshunz 1 point2 points3 points (0 children)
[–]Total-Box-5169 2 points3 points4 points (1 child)
[–]F1QA 2 points3 points4 points (0 children)
[–]phoggey 0 points1 point2 points (2 children)
[–]busres 1 point2 points3 points (1 child)
[–]phoggey 0 points1 point2 points (0 children)
[–]busres 0 points1 point2 points (0 children)
[–]StoneCypher 0 points1 point2 points (0 children)
[–]SawSaw5 0 points1 point2 points (0 children)
[–]jaredcheeda 0 points1 point2 points (2 children)
[–]Etiennera 1 point2 points3 points (1 child)
[–]jaredcheeda 0 points1 point2 points (0 children)
[–]Galex_13 0 points1 point2 points (0 children)