Why Use .flat() ?

There will be times as a Javascript Developer when you have to transform a nested or multi-dimensional array to a one-dimensional array. Let’s see how we can flatten an arry with the new .flat method

Array.prototype.flat() 101

The flat method can take in an optional argument , a number, to specify the depth the array should be flattened. That way you can flatten multidimensional arrays. We will show ample examples

	
	const sportsIconArray = [ ['Basketball',  'πŸ€'], ['Football', '🏈'] , ['Tennis' ,'🎾']  ];

	const sportIconsFlat = sportsIconArray.flat();
		// Remember the default argument passed in is one
		// You never have to write .flat(1)

	console.log(sportIconsFlat);
     ['Basketball',  'πŸ€', 'Football', '🏈' , 'Tennis' ,'🎾']
	
Wait ? Did .flat() go two arrays deep ?

You may be thinking that in the previous example .flat went two layers deep. Since for us to get to say ‘Basketball’ we have to go past two square brackets. However, if we remember .flat() is called on the array.prototype. So where already starting one deep before we call the .flat() method

Flattening Deeply Nested/Multi-dimensional Arrays

In the last example we did an array nested one deep. Now let’s try one nested two deep

	
	const sportsType = [
	[
		'Dry Sports', ['Basketball',  'πŸ€'], ['Football', '🏈'], ['Tennis' ,'🎾'], ['Pool',  ' 🎱']
	],
	[
		'Wet Sports', ['Surfing', 'πŸ„'], ['Swimming', ' 🏊'], ['Rowing', 'πŸš£β€β™€οΈ']
	]
];

	

Now let’s say we just want this all in one array. With the dry sports and wet sports together in the same array. Let’s see how we’d go about this

	
		const sportsTypeFlat = sportsType.flat(2);
		console.log(sportsTypeFlat);
		// ['Dry Sports', 'Basketball',  'πŸ€', 'Football', '🏈', 'Tennis' ,'🎾', 'Pool',  ' 🎱', 'Wet Sports', 'Surfing', 'πŸ„', 'Swimming', ' 🏊', 'Rowing', 'πŸš£β€β™€οΈ']
	
Flattening an Array of Unknown Depth

Now if you have an array, and you don’t know how deeply nested is you can pass infinity into the flat method

	
	const sportsTypeNested = [
	[
		'Dry Sports', ['Basketball',  ['πŸ€'] ], ['Football', ['🏈'] ], ['Tennis' , ['🎾'] ], ['Pool',   ['🎱'] ]
		],
		['Wet Sports', ['Surfing', ['πŸ„'] ], ['Swimming', ['🏊'] ], ['Rowing', ['πŸš£β€β™€οΈ'] ]]
	];

	const sportsTypeFlat = sportsTypeNested.flat(Infinity);
	//Make sure infinity starts with a capital
	
	console.log(sportsTypeFlat);
	// ['Dry Sports', 'Basketball',  'πŸ€', 'Football', '🏈', 'Tennis' ,'🎾', 'Pool',  ' 🎱', 'Wet Sports', 'Surfing', 'πŸ„', 'Swimming', ' 🏊', 'Rowing', 'πŸš£β€β™€οΈ']
	
Further Reading


Now you should be comfortable flattening an array. However there will be situations where you will have to transform, an array before it’s flattened. Like let’s say we wanted to lowercase or uppercase all of the sports names before flattening. flatMap() has arrived article coming Jan 23rd