AppDividend
Latest Code Tutorials

Javascript Array Flat Example | Array.prototype.flat() Tutorial

0

Javascript Array Flat Example | Array.prototype.flat() Tutorial is today’s topic. Javascript Array flat() method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth. It returns a new array with the sub-array elements concatenated into it.

Javascript Array Flat Example

As its name suggests, the Array flat() method available on an Array prototype returns the new array that’s the flattened version of an array it was called on. If we do not provide arguments passed-in, then the depth of 1 is assumed.

The syntax of Javascript Array flat() method is following.

let newArray = arr.flat([depth]);

The depth level is specifying how deep a nested array structure should be flattened. Defaults to 1. It is an optional parameter.

Let’s see the following example.

// app.js

const arr = [['krunal', 'ankit'], [21, 74]];

console.log(arr.flat());

The output is following.

 

Javascript Array Flat Example | Array.prototype.flat() Tutorial

In the above example, by default, the depth level is 1. Let’s see the example where depth level is more than 1.

// app.js

const arr = [['krunal', 'ankit'], [21, 74], ['appdividend', ['Laravel', 'Angular']]];

console.log(arr.flat(2));

The output is following.

 

Javascript Array Flat Example

You can use Infinity if you need to flatten an array of the arbitrary depth.

See the following example.

// app.js

const arr = [['krunal', 'ankit'], [21, 74], ['appdividend', ['Laravel', 'Angular', ['easy']]]];

console.log(arr.flat(Infinity));

The output is following.

 

Array.prototype.flat() Tutorial

Flattening and array holes

The flat method removes empty slots in arrays. See the following example.

// app.js

const arr = ['WhatsApp', 'Facebook', , 'Twitter'];

console.log(arr.flat());

See the following output.

 

Flattening and array holes

Finally, Javascript Array Flat Example | Array.prototype.flat() Tutorial is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.