Can someone explain me what Array.prototype.concat.apply([], arr); do? Thanks

Tell us what’s happening:
So i solved the challenge of the nested arrays but i mostly did it because i searched it on google.I found the command var arr = Array.prototype.concat.apply([], arr); which actually solved the problem,all the rest code is written by me.So can someone explain me what does this command actually does,i mean i know what concat does but the apply method is the first time i see it and i am bit confused.Even i solved the challenge i don’t wanna have ‘gaps’ on my learning curve.Thanks!

Your code so far


function steamrollArray(arr) {
  var arr = Array.prototype.concat.apply([], arr);
  let isFlat = false;

  for(let i=0;i<arr.length;i++){
    if(Array.isArray(arr[i])){
      return steamrollArray(arr)
    }
  }
    return arr;
}

console.log(steamrollArray([1, [2], [3, [[4]]]]));

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83 Safari/537.36.

Challenge: Steamroller

Link to the challenge:

Hello there,

One of your first point of calls should probably be the Mozilla Docs. As for my explanation:

In the same way we have the method concat which happens to be an Array method, we have the apply method, which happens to be a Function method.

It is not all that special, in this context, because it does exactly what it sound like: It applies the provided arguments to the mentioned function

In your case:

var newArr = Array.prototype.concat.apply([], arr);
  • Array.prototype.concat is the function to be used by apply
  • [] is the object the function will be invoked upon
  • arr is the argument to be passed to the function

So, all this line does is:

var arr = [].concat(...arr); // Spread operator used here

There is nothing more to this use case.

Summary: apply calls the concat method on each element in the arr.

I hope this helps somewhat.