Array Flat in JavaScript

Level 3123 keystrokes

flat() creates a new array with sub-array elements flattened to a specified depth.

JavaScript code

// Create a nested array (2D array)
1const nested = [[1, 2], [3, 4], [5, 6]];
// flat() with no argument flattens one level deep
// Converts nested arrays into a single array
2const flat = nested.flat();
// Print flattened array [1, 2, 3, 4, 5, 6]
3console.log(flat);
// flat(2) flattens two levels deep
// [1, [2, 3]] becomes [1, 2, 3]
4console.log([[1, [2, 3]]].flat(2));

Output

[ 1, 2, 3, 4, 5, 6 ]
[ 1, 2, 3 ]
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this JavaScript code and how often they appear.

  • ,× 7
  • [× 7
  • ]× 7
  • ;× 4
  • .× 4
  • (× 4
  • )× 4
  • =× 2

More JavaScript examples at level 3

← JavaScript typing practice