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

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
JavaScript
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.


Comments

If you liked this post, you might like these ones, too

  1. Squishy button active state

    🔥 A handy quick tip.

    Continue
  2. Use a set to remove array duplicates

    🔥 A handy quick tip.

    Continue
  3. Add inline SVG directly in your CSS

    🔥 A handy quick tip.

    Continue

Become a supporter by joining the Piccalilli Membership

For as little a $5 per month, you can get access to a private, friendly community, get a weekly newsletter and help to make as much content free as possible around here. If you join the $10 per month supporters club, you get access to premium tutorials and free access to mini courses!

Become a member

Sign up for updates

Stay up to date with updates from Piccalilli. You’ll get alerted as soon as any new content gets published. You’ll also get updates on upcoming courses and membership features! You can unsubscribe at any time, too.