Javascript Array flat()

Introduction

The flat() method flats nested multi-dimensional array by level.

var newArray = arr.flat([depth]);
  • depth - Optional, how many level down to nested array structure. Defaults to 1.
const arr1 = [1, 2, [3, 4]];//from   w  w  w .j a va2 s  .c o m
let a = arr1.flat(); 
console.log(a);// [1, 2, 3, 4]

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

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

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

The flat() method removes empty slots in arrays:

const arr5 = [1, 2, , 4, 5];/*  ww  w  .  j a  v  a 2 s .  c om*/
let a= arr5.flat();
console.log(a);// [1, 2, 4, 5]



PreviousNext

Related