Sometimes when you have an array of arrays, you may want to condense them into a single array, putting all of the values of the inner arrays into the single outer array. You can do that easily with the Array
flat() is called on any array and will return a new array that is a flattened version of the original.
let nested = [[1,2],,[4,5]]; let flattened = nested.flat(); console.log(flattened); // [1,2,3,4,5]
flat() also accepts a depth argument which lets you specify how many nested arrays should be flattened. By default this is 1.
let nested = [1,[2,[3,[4,]]]]; let flatOne = nested.flat(); // [1,2,[3,[4,]]] console.log(flatOne); let flatTwo = nested.flat(2); // [1,2,3,[4,]] console.log(flatTwo); let flatFour = nested.flat(4); // [1,2,3,[4,]] console.log(flatFour); // [1,2,3,4,5]
flat() only works with other arrays. It does not flatten iterables or array-likes in the original array.
flat() can be useful for is converting a multi-dimensional array into a single dimension array to make it easier go through all the elements without having to worry about nested loops.
let ticTacToeBoard = [ ['X', 'O', ' '], ['O', 'X', ' '], ['X', 'O', 'X'], ]; let allMarks = ticTacToeBoard.flat(); console.log(allMarks); // [X, O, , O, X, , X, O, X] let numXs = allMarks.filter(mark => mark === 'X').length; console.log(numXs); // 4
There’s also a version of
map() with built-ing flattening called
flatMap(). This would be similar to calling both
map() but does them as a single operation. We’ll look at an example that uses this in a future tip.