how does this concat command work with this array?

Viewed 99

I came across this JS problem but I can't figure out the syntax of how it's working, could someone please help to explain? I don't understand the empty square bracket syntax at the start and then how the concat is being applied with another empty square bracket? it's just quite confusing for me.

Appreciate any help to step through this.

let arr = [[1, 2],[3, 4],[5, 6, 7, 8, 9],[10, 11, 12]];

let flattened = [].concat.apply([], arr);
// [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ]
3 Answers

So let's go step by step.
[].concat() is just the function, because apply is not called to a regular element, but a function. the [] in front is used just so you could call the concat as it's a method for arrays. The apply() method calls a function with a given this value, and arguments provided as an array.
So the [].concat.apply([], arr) has 3 parts:

  • concat - the function which is used
  • [] - the element to which the function is called (first param of the apply provided)
  • arr - array of elements which are passed to the used function each time

So under the hood it would look like this:

[].concat([1, 2]).
  .concat([3, 4])
  .concat([5, 6]) //etc

And then the concatenated array is returned and stored into the flattened. Now each sub-array of the arr has been concatenated to one another and results in a simple array [1, 2, 3, 4, 5, 6, ...]

The [] is an empty array. The concat function concatenate two or more arrays: [].concat(arr[0], arr[1], arr[2], arr[3])

The catch here is to know how apply works. The second parameter of apply is an array of parameters. It's like doing this (if you're familiar with the concept of desctructuring): [].concat(...arr)

You can read more about apply here

let arr = [[1, 2],[3, 4],[5, 6, 7, 8, 9],[10, 11, 12]];

let flattened = [].concat.apply([], arr);
*first array*---|                |---*second array*
           

The first array has one goal:

  • to invoke concat() method with this. Here this is the second array. Then the first array is thrown away

Then apply() method flattens the arr array to one level. You can check it:

let foo = [0].concat([1,2,3], [[1,2,3]] ); 
console.log(foo)

UPDATE:

In addition, the first array can be removed:

const arr = [[1, 2],[3, 4],[5, 6, 7, 8, 9],[10, 11, 12]];

const flattened = Array.prototype.concat.apply([], arr);
console.log(flattened)

Some info how apply() works.

In addition, it would be really useful to know how apply() flattens array items to one level or how apply() takes an array of arguments and treats each element of that array as a single argument.

Let me show a simple example. We have the following object and method:

const showFullName = (arg_1, arg_2) => {
    console.log(`arg_1 is ${arg_1}`);
    console.log(`arg_2 is ${arg_2}`);
}

let foo = {};
showFullName.apply(foo, ['firstName', 'surname']);

Related