Streamroller doesn't pass the test - SOLVED SPOLIER

Hi,
I’m doing this code and it seems to work ?
I’m using a New Incognito Windows in Chrome too, here the salt.

let array= [];
let steamrollArray = function (arr){
  for (let i = 0, l = arr.length; i < l; i++) {
    var v = arr[i];
    if (Array.isArray(v)) {
      steamrollArray(v);
    }else if(typeof v === 'object'){
      array.push({});
    }else {
      array.push(v);
    }
  }
  return array;
};
let res = function () {
  steamrollArray([1, [2], [3, [[4]]]]);
  //console.log(array);
  return array;
}();
1 Like

I forgot the global var again…
thanks.

If I put my code in iife, it doesn’t work, but I don’t understand why ?

(function(window) {
  let array= [];
  let steamrollArray = function (arr){
    for (let i = 0, l = arr.length; i < l; i++) {
      var v = arr[i];
      if (Array.isArray(v)) {
        steamrollArray(v);
      }else if(typeof v === 'object'){
        array.push({});
      }else {
        array.push(v);
      }
    }
    //return array;
  };
  let res = function () {
    steamrollArray([1, [2], [3, [[4]]]]);
    console.log(array);
    return array;
  }();

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

Because the function gets created, executed and then discarded. There is nothing to call.

I’m trying to defined the varaible with a context, doesn’t work ?

let steamrollArray = function (arr){
  if (typeof array == 'undefined') {
    let array = []
  }
  for (let i = 0, l = arr.length; i < l; i++) {
    var v = arr[i];
    if (Array.isArray(v)) {
      steamrollArray(v);
    }else if(typeof v === 'object'){
      array.push({});
    }else {
      array.push(v);
    }
  }
  console.log(array);
  return array;
};

steamrollArray([1, [2], [3, [[4]]]]);
    ...
if (typeof array == 'undefined') {
    let array = []
}
    ...

Where do you define array?
let will be scoped only to if.

In my function loop I don’t have access to the argument in steamrollArray(arr), I don’t undertand this point here ?
EDIT: Thank you for your help

EDIT: I find a solution can I post it the solution or don’t show it?

This is your thread so I think you can post the solution, just edit the title and add [SOLVED] and [SPOILER].

1 Like
function steamrollArray(arr) {
  let tab = [];
  arr.forEach(function loop(item) {
    if (Array.isArray(item)) {
      // If is array, continue repeat loop
      item.forEach(loop);
    }else if(typeof v === 'object'){
      //console.log(item);
      tab.push(item)
    }else {
      //console.log(item);
      tab.push(item)
    }
  })
  console.log(tab);
  return tab
}
steamrollArray([1, [2], [3, [[4]]]]);

These two elses are doing the same thing, so why not make them one?

1 Like

I want to be sure to pass the test, but true the Array is an ‘object’.
Thanks