How concat() and apply() flattens an array?

When I saw the following piece of code, I was a little bit amazed how it works. So let’s jump to know how it works.

Let’s say we have the following code:

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

So, we can name arrays by name to be cleaner:

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.

It is just how apply() works.

That’s all:)

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']);

The output will be:

arg_1 is firstName
arg_2 is surname

I am software engineer. I like to learn and like to develop software. I program with C#, SQL and JavaScript