Need help with understaning Javascript Intermediate Algorithm: Steamroller

Need help with understaning Javascript Intermediate Algorithm: Steamroller
0

#1

Can someone explain to me the execution steps of the following two code? I tried a lot but I can’t seem to understand what’s going on :frowning:

function steamrollArray(arr) {
  let flat = [].concat(...arr);
  return flat.some(Array.isArray) ? steamrollArray(flat) : flat;
}

flattenArray([1, [2], [3, [[4]]]]);
function steamrollArray(arr) {
  return arr.toString()
    .replace(',,', ',')       // "1,2,,3" => "1,2,3"
    .split(',')               // ['1','2','3']
    .map(function(v) {
      if (v == '[object Object]') { // bring back empty objects
        return {};
      } else if (isNaN(v)) {        // if not a number (string)
        return v;
      } else {
        return parseInt(v);         // if a number in a string, convert it
      }
    });
}

#2

where did you get the code from?


#3

Your code has been blurred out to avoid spoiling a full working solution for other campers who may not yet want to see a complete solution. In the future, please do not post full working solutions to the challenges. If you have a specific question about how a particular part of code works, just post that specific part and ask your question.

If you took these solutions from the Guide, then they should already have explanations.

If you are having trouble understanding any of the solutions you posted, I would ask if you have solved this challenge on your own yet? If not, then I suggest trying to solve it on your own and then review these solutions later. Once you solve it in your own way, you will have a better chance of understanding how these solutions create a working solution.

If you have not solved this challenge yet and are struggling with it, then it would be better for you to post your current attempt at the solution or post questions about which parts of the challenge instructions you do not understand.

Thank you.


#4

It’s the solution of the challenge Javascript Intermediate Algorithm: Steamroller.


#5

there are many ways to solve this challenge. The second solution for eg uses a parsing method to flatten the array. While the first method makes a copy of the array and then checks the elements in the array to see if they are themselves arrays and if so, it calls itself to flatten these elements (utilizing something called recursion).