JavaScript

June 5, 2023

How to use JavaScript Array flat()

Program to use JavaScript Array flat() method


let a = [[1,2,3],[4,5],[6,7]];
let b = a.flat();
console.log(b);

Output


[
    1, 2, 3, 4,
    5, 6, 7
]

Steps Description

  1. Declare two variables a and b
  2. Initialize two variables a and b with value of strings a = [[1,2,3],[4,5],[6,7]] and b
  3. The array flat() method converts a nested array to a new array.
  4. The value of b variable is displayed with the help of console.log inbuilt function

Program to use JavaScript Array flat() method


let c = [[1,2],[3,4,5,[6,7],8],[9,10]];
let d = c.flat(2);
console.log(d);

Output


[
    1, 2, 3, 4,  5,
    6, 7, 8, 9, 10
]

Steps Description

  1. Declare two variables c and d
  2. Initialize two variables c and d with value of strings c = [[1,2],[3,4,5,[6,7],8],[9,10]] and d = c.flat(2)
  3. The array flat() method converts a nested array to a new array.
  4. The value of d variable is displayed with the help of console.log inbuilt function

by : Suhel Akhtar

Quick Summary:

JavaScript Array flat() method