I came across this stackoverflow question about recursively flattening a JS array. Here is the accepted answer:
function flatten() {
var flat = [];
for (var i = 0; i < arguments.length; i++) {
if (arguments[i] instanceof Array) {
flat.push.apply(flat, flatten.apply(this, arguments[i]));
} else {
flat.push(arguments[i]);
}
}
return flat;
}
flatten([[1], 2, [3, 4]]); // returns [1, 2, 3, 4]
I'm having trouble understanding how flat.push.apply(...)
and flatten.apply(...)
work.
I understand that the function will only exit if none of the items in the array are arrays themselves. I also understand that Function.prototype.apply()
allows you to call a function using an array of arguments.
What I don't understand is why you are using flat.push...
if flat
will be set to []
at each function iteration. Also, what significance does setting flat
as the this
context have?
Can someone help explain how the execution of flat.push.apply(flat, flatten.apply(this, arguments[i]));
works?