Flattening nested arrays (review my solution)

are there any downsides to my solution to flattening nested arrays

function steamrollArray(arr) {
  if (arr.length == 0) return [];
  let c = arr.shift();

  if (typeof c == "object") {
    if (c instanceof Array == false) return [c, ...steamrollArray(arr)];
    return [...steamrollArray(c), ...steamrollArray(arr)];
  } else {
    return [c, ...steamrollArray(arr)];
  }
}

let c = steamrollArray([1, {}, [3, [[4]]]]);
console.log(c);

I see the following referenced 3 times:

 ...steamrollArray(arr)]

Just use the spread operator one time for this line and reuse it in the other places.

I also see return [c, ...steamrollArray(arr)] twice. See if you can make your code DRY (Do Not Repeat Yourself).

1 Like