Confused. don’t understand - [].concat.apply([],arr)

https://forum.freecodecamp.org/t/confused-dont-understand-concat-apply-arr/15180

Hi,

I’m on one of the algorithm challenges - “Sorted Union”, where one of the things we have to do is flatten an array of arrays.

E.g.
> var arr = [[0],[1],[2],[3],[4],[5]];
> var rslt = Array.concat.apply([],arr);
> console.log(rslt) // [0,1,2,3,4,5]

It seems straightforward but I’m missing something. How does this work?
I looked at the documentation for Array.prototype.concat() on https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat 223, but still didn’t understand the above code.

I understand a.concat(b) produces [a,b] (e.g. [1,2].concat([3,4]) === [1,2,3,4]),
but how/why does it flatten the array one level?

i.e. Why is Array.concat.apply( [], [1, [2], [3, 4]] ) === Array.concat(1, [2], [3,4]) ??? (result is [1,2,3,4]) in both cases

Thanks,

  • Jay
 
 
 

Thanks for the link Selhar1.
In a few words:

Apply Structure: myFunction.apply(thisVal,argsArray):

  • myFunction: Just the function to be executed.
  • thisVal: The context.
  • argsArray: The arguments from myFunction. Where argsArray = [arg1,arg2,arg3,…]

myFunction.apply(thisVal,argsArray) == thisVal.myFunction(arg1,arg2,arg3,…)

Array.prototype.concat([],[[1,2],[3,4]]) == [ ].concat([1,2],[3,4])

A new use for Apply :wink:

posted on 2020-11-12 11:10  bowen_tong  阅读(47)  评论(0)    收藏  举报