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.
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 aD
this
argument of a new Array, to be the base Object andE
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With