Steamroller function returns null value for empty arrays

Steamroller function returns null value for empty arrays
0

#1

Hello,

I’m trying to figure out how to get my solution for the Steamroller problem to stop returning the null value. If run this now, it returns [1, 2, null, 3, 4]:

function steamrollArray(arr) {
  // I'm a steamroller, baby
  var roller = function roller(x) {
    if (Array.isArray(x)===true){
      for (var i = 0; i < x.length; i++) {
        return roller(x[i]);
      }
    }
    else {
      return x;
    }
  };
  var newArr=[];
  for (var j = 0; j < arr.length; j++) {
    if (arr[j].length > 1) {
      for (var k = 0; k < arr[j].length; k++) {
        newArr.push(roller(arr[j][k]));
      }
    }
    else {
      newArr.push(roller(arr[j]));
    }
  }
  return newArr;
}

steamrollArray([1, [2], [], [3, [[4]]]]);


I have tried running a loop at the end to weed out null values, but that does not work, (for loop, if val !==null, push it onto a new array and return that.).

Please help?


#2

I cleaned up your code.
You need to use triple backticks to post code to the forum.
See this post for details.

if (arr[j].length > 1) {
   //...
} else {
   // Think about what happens here if arr is empty
   newArr.push(roller(arr[j]));
}

#3

I’m guessing it tries to return the [j] index of that array, which is null; I’m not sure how to get around it… I tried:

if (arr[j].length>1){
//...
}
else if (roller(arr[j]) !== null){
  newArr.push(roller(arr[j]));
}

But that doesn’t help at all. I also tried testing with

else if (arr[j].length === 1){
  newArr.push(roller(arr[j]));
}

But because the length of the first character, which is not in an array, is empty, that excludes the first character.

Also, it seems like my function is going to be SUUUUPER slow with larger arrays because I have a triple-nested loop…


#4

This is the closest of your two attempts, but it’s strange that you’re testing the output of your function rather than the array itself.

This is a really good intuition to have, but just get the algorithm working before you optimize. It’s in the nature of nested arrays to be slow, so don’t worry about a solution that may not exist.


#5

I tried testing the array itself, via things like:

if (typeof(arr[j][0]) === undefined) {
.....
}

or

if (arr[j] === []) {
....
}

but neither of those worked either… Not trying to get someone to just “give me the answer” or anything, but why can I not weed out these null values by directly checking them? None of my checks seem to catch them.

Edit:
Before I sound too ungrateful; thanks to you, PortableStick, and thanks to everyone who posts here. This is the first time I’ve been unable to get through a problem with just the “Read-Search” steps, and that’s all thanks to the people here.


#6

I did end up figuring this out. Thanks!