Skip to content

Array flat()

The flat() method available on the Array prototype returns a new array that’s a flattened version of the array it was called on. The default value(if no value is entered) is 1 .

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

depth: if a number is passed-in as the first argument, it’s used as the maximum depth to flatten the array.


Examples

Example 1

        let names = [ ["alex", "rick"] , ["johny", "sasha"]];
        let flatNames = names.flat();
        console.log( flatNames )

output:

[“alex” , “rick” , “johny” , “sasha”]


Example 2

        let cars = [["audi", "toyota"], ["ferrari", ["camaro", ["bmw"]], "porsche"]];

        let flatCars1 = cars.flat( 1 );
        let flatCars2 = cars.flat( 2 );
        let flatCars3 = cars.flat( 3 );

        console.log( flatCars1 );
        console.log( flatCars2 );
        console.log( flatCars3 );

output:

[“audi”, “toyota”, “ferrari”, Array(2), “porsche”]
[“audi”, “toyota”, “ferrari”, “camaro”, Array(1), “porsche”]
[“audi”, “toyota”, “ferrari”, “camaro”, “bmw”, “porsche”]

if we want to return all them as a new array.

        let cars = [["audi", "toyota"], ["ferrari", ["camaro", ["bmw"]], "porsche"]];

        let flatCars = cars.flat(Infinity);

        console.log( flatCars );

output:

[“audi”, “toyota”, “ferrari”, “camaro”, “bmw”, “porsche”]


Example-3

        var arr = [1, 2, , 4, 5];
        console.log(arr.flat())

output:

[1, 2, 4, 5]


Browser Support

Chrome69
Edgeno
Firefox62
Internet ExplorerNo
Opera56
Safari12
Android webview69
Chrome for Android69
Edge mobileno
Firefox for Android62
Opera Android56

3 Comments »

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

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

%d bloggers like this: