While first index is an Array

I thought maybe I was getting an infinite loop, because .push wasn’t reducing the length of arr., so it’s always an array. But it appears to be falling through the while loop all together… am I not checking the first index correctly?

function steamrollArray(arr) {
  var R2 = [];
  while (arr[0].isArray) {
    console.log(arr[0]);
    R2.push(arr[0]);
    return R2;
  }
  return R2;
}

steamrollArray([[["a"]], [["b"]]]); // should return ["a", "b"].
steamrollArray([1, [2], [3, [[4]]]]); // should return [1, 2, 3, 4].
steamrollArray([1, [], [3, [[4]]]]); // should return [1, 3, 4].
steamrollArray([1, {}, [3, [[4]]]]); // should return [1, {}, 3, 4].

Don’t reinvent the wheel. There are lots of snippets to do this on StackOverflow:

function flatten(arr) {
  return arr.reduce( (flat, toFlatten) => {
    return flat.concat(Array.isArray(toFlatten) ? flatten(toFlatten) : toFlatten);
  }, []);
}

flatten([[["a"]], [["b"]]]); // ["a", "b"]
flatten([1, [2], [3, [[4]]]]); // [1, 2, 3, 4]
flatten([1, [], [3, [[4]]]]); // [1, 3, 4]
flatten([1, {}, [3, [[4]]]]); // [1, {}, 3, 4]

copying someone else’s code is easy… I’m trying to understand why my while loop is not being caught.

I can see it’s falling through from frame 3 to 4… https://goo.gl/K5VYn3

That’s because you need to call isArray on Array and pass in the thing you want to test for arrayness as an argument.

Array.isArray(arr[0])
// true
1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.