Array.concat() method to flatten a multi-dimensional array. This method works in all modern browsers, and IE6 and above.
Here is an example:
const animals = [ ['🐍'], ['🐢'], ['🐝'], ['🐉'], ['🐋'] ]; const flattened = .concat.apply(, animals); console.log(flattened); // ['🐍', '🐢', '🐝', '🐉', '🐋']
apply() method is a part of
concat() function's prototype that calls the function with a given
this value, and arguments provided as an array.
Alternatively, you could use the ES6 syntax to make the above example super concise:
const flattened = .concat(...animals); console.log(flattened); // ['🐍', '🐢', '🐝', '🐉', '🐋']
The spread operator (
...), we used above, is only available in modern browsers, and doesn't work in IE.
You can also use the
Array.reduce() method along with
Array.concat() to flatten a multi-dimensional array to a one-dimensional array:
const flowers = [['🍀'], ['🌷'], ['🌹'], ['🌻']]; const flattened = flowers.reduce((flat, val) => flat.concat(val), ); console.log(flattened); // ['🍀', '🌷', '🌹', '🌻']
The above approach works in all modern browsers, and IE9 and higher.
ES2019 introduced two new methods to
Array.flat() method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth:
const animals = [ ['🐍'], ['🐢'], ['🐝'], ['🐉'], ['🐋'] ]; const flattened = animals.flat(); console.log(flattened); // ['🐍', '🐢', '🐝', '🐉', '🐋']
By default, the depth level is 1. You can pass in an integer to the
flat() method to specify how deep a nested array structure should be flattened. Use the
Infinity keyword to set it to infinite:
// default depth level ['🍀', ['🌷', ['🌹', '🌻']]].flat(); // ['🍀', '🌷', ['🌹', '🌻']] // depth level: 2 ['🍀', ['🌷', ['🌹', '🌻']]].flat(2); // ['🍀', '🌷', '🌹', '🌻'] // depth level: infinite ['🍀', ['🌷', ['🌹', '🌻']]].flat(Infinity); // ['🍀', '🌷', '🌹', '🌻']
Array.flatMap() is identical to a Array.map() followed by a
Array.flat() of depth level 1. This method iterates each element of the array by using a mapping function, and then flattens the results into a new array:
const strings = ['Today is', 'a very', '', 'special day']; const result = strings.flatMap(str => str.split(' ')); console.log(result); // ["Today", "is", "a", "very", "", "special", "day"]
flat() method is useful when you want to manipulate the nested arrays before they are flattened into a single-dimensional array.
👋 If you enjoy reading my articles and want to support me to continue creating free tutorials, ☕ Buy me a coffee (cost $5) .
Need help to launch a new product? I am available for contract work. Hire me to accomplish your business goals with engineering and design.