Linked Questions

Popular Questions

Recursively flattening an array (why is my function not working?)

Asked by At

So I am trying to get my head around recursion and recently came across a problem which was easiest solved using recursion anyway. I am trying to flatten an array of varying depth arrays and the function I cam up with to do this was:

mixedArray = [1, 2, [3, 4], [[5, 6], 7], 8, 9];

function flattenArray(array) {
 return array.map(val => {
  if (typeof val !== "number") {
   return flattenArray(val);
  } else {
   return val;
  }
 });
}

console.log(flattenArray(mixedArray));

Now, I am expecting this to output [1,2,3,4,5,6,7,8,9] but it just returns mixedArray as is. My thinking was that it takes the array and (assuming that the array is not just a single number) maps through the entries. If an entry is a single number then it should return that number if it is not, then it should call the original function on this entry, and so on and so forth. Hopefully this is something fairly basic like a syntax error (which would be fairly typical!!)

Please note; I would like to know WHY my function is not working as well as looking at a solution.

Thanks (in advance)

Related Questions