Convert a 2D array into a flat, 1D array of unique items

Categories

Convert a messy multidimensional array into a nice single dimension array of unique items.


If you have an array that’s multidimensional, and that contains duplicated data: you can get a flat, unique version, using modern, ES2019 JavaScript capabilities.

Code language
js
const allAnimals = [
	["Cat", "Dog", "Quokka", "Possum"], 
	["Quokka"], 
	["Quokka", "Elephant", "Giraffe"], 
	"Cat", "Possum"
];

const filteredAnimals = [...new Set(allAnimals.flat())];

The flat() prototype method grabs each nested array and returns back a single-level, flat array, containing all the data.

What we then do is use a new Set instantiation to discard any duplicates. Lastly, we use the spread syntax to convert that back into an array.

Hello, I’m Andy and I’ll help you to level up your front-end development skills.

I'm a designer and front-end developer who has worked in the design and web industries for over 15 years, and in that time, I have worked with some of the largest organisations in the world, like Google, Harley-Davidson, BSkyB, Unilever, The Natural History Museum, Oracle, Capita, Vice Media and the NHS.

On Piccalilli, I share my knowledge and experience to make you a better front-end developer.

I'm the founder of Set Studio, a creative agency that specialises in building stunning websites that work for everyone. Check out what we're all about.