;

Javascript Array - flat() Method


Tutorialsrack 01/10/2022 Jquery Javascript

In this article, you will learn about the javascript Array built-in method Array.prototype.flat().  How does this method work in javascript? 

Array.prototype.flat()

This Array.prototype.flat() method returns a new array with all sub-array elements merged into it recursively till the specified depth.

Syntax
array.flat(depth);

This method takes one parameter which is optional:

  • depth(optional): this parameter is used to specify the depth level of how deep a nested array structure should be flattened. Defaults to 1.

The flat() method is a copying method and does not alter this instead this method returns a shallow copy of the array that contains the same elements as the one from the original array. 

If an array has empty slots, you can simply use the flat() method to remove the empty slots.

Here are some examples of Array.prototype.flat() method:

Examples
const arr1 = [0, 1, 2, [3, 4]];
console.log(arr1.flat())
//Output => [0, 1, 2, 3, 4]

const arr2 = [0, 1, 2, [3, 4, [5, 6]]];
console.log(arr2.flat())
//Output => [0, 1, 2, 3, 4, [5, 6]]

const arr3 = [0, 1, 2, [3, 4, [5, 6]]];
console.log(arr2.flat(2))
//Output => [0, 1, 2, 3, 4, 5, 6]

const arr4 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]];
console.log(arr4.flat(Infinity));
//Output => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


//Remove empty slots using flat() method

const arr5 = [1, 2, , 4, 5];
console.log(arr5.flat()); 
//Output => [1, 2, 4, 5]

const arr6 = [1, , 3, ["a", , "c"]];
console.log(arr6.flat()); 
//Output => [ 1, 3, "a", "c" ]

const arr7 = [1, , 3, ["a", , ["d", , "e"]]];
console.log(arr7.flat()); 
//Output => [ 1, 3, "a", ["d", empty, "e"] ]

console.log(arr7.flat(2)); 
//Output => [ 1, 3, "a", "d", "e"]

I hope this article will help you to understand the javascript Array built-in method Array.prototype.flat()

Share your valuable feedback, please post your comment at the bottom of this article. Thank you!


Related Posts



Comments

Recent Posts
Tags