Javascript Array Flat: How to Flat Array in JavaScript

0
8
Flatten a nested array in Javascript

Javascript Array flat() is an inbuilt method that 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()

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.

Syntax

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

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

Parameters

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());

See the output.

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

See the output.

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

See the output.

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 Tutorial is over.

Leave A Reply

Please enter your comment!
Please enter your name here

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