Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does using specifically "[]" as a parameter work?

I was doing some javascript exercises online (codewars.com). One problem asked the user to take an array of array objects and remove one level from the entirety of the array.

[] /* becomes */ []
[[1, 2, 3], ["a", "b", "c"], [1, 2, 3]] /* becomes */ [1, 2, 3, "a", "b", "c", 1, 2, 3]
[[3, 4, 5], [[9, 9, 9]], ["a,b,c"]] /* becomes */ [3, 4, 5, [9, 9, 9], "a,b,c"]

I ended up learning about the concat method, but the most popular solution used this statement...

function (arr){
  return [].concat.apply([],arr);
}

Can someone please explain the usage of [] here? I can't understand how this produces the correct results (and it doesn't give explanation on the page). I know that there are plenty of other times in which empty brackets are used as parameters and labeling arrays so understanding the usage here may help me be able to use it myself in the future.

like image 260
JoeL Avatar asked Nov 09 '15 15:11

JoeL


1 Answers

Lets split this across multiple lines so it is easier to describe. The description of line D specifically is what answers your question

[]          // A
    .concat // B
    .apply( // C
        [], // D
        arr // E
    );
  • A Is an Array, but here it is just being using as a shortcut to Array.prototype so we can access..
  • B The concat method from Array.prototype
  • C which we then invoke (using apply) with a
  • D this argument of a new Array, to be the base Object and
  • E a list of arguments, which was our previous arr

So, you could re-write this using Array.prototype and call as

var new_base_arr = [];
Array.prototype.concat.call(
    new_base_arr,
    arr[0],
    arr[1],
    ...
    arr[n]
);

Which might look more familiar to you written as

new_base_arr.concat(arr[0], arr[1], ..., arr[n]);

The problem being solved here is invoking a function with an undetermined number of arguments.

like image 188
Paul S. Avatar answered Oct 06 '22 01:10

Paul S.