Flattening Arrays
Version: ES2019
Level: Beginner
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()
method. flat()
is called on any array and will return a new array that is a flattened version of the original.
let nested = [[1,2],[3],[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,[5]]]]];
let flatOne = nested.flat(); // [1,2,[3,[4,[5]]]]
console.log(flatOne);
let flatTwo = nested.flat(2); // [1,2,3,[4,[5]]]
console.log(flatTwo);
let flatFour = nested.flat(4); // [1,2,3,[4,[5]]]
console.log(flatFour); // [1,2,3,4,5]
Note that flat()
only works with other arrays. It does not flatten iterables or array-likes in the original array.
One thing 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 flat()
and map()
but does them as a single operation. We’ll look at an example that uses this in a future tip.
More info: