A Unique Array of Strings
But it’s also a real-life problem. Maybe your React app needs to find a list of all of the unique email addresses for your clientele.
Method 1 — Use Set to Find Unique Strings
Set is awesome for finding unique primitive values, including strings. You can create a new array containing just the unique strings from another array in just one line of code.
Here’s how it works:
As you can see in the code example,
Array.from() is equivalent to using the square brackets
 with the
... spread operator.
For most cases,
Set is going to be all you need. But let’s look at two other methods of removing non-unique strings from an array.
If you don’t want to use
Set, you could loop through an array using a
Here’s what that would look like:
undefined, which is a falsy value, meaning it evaluates to
false in an
if statement or other conditional, like the
? ternary operator.
For comparison, variables that haven’t been declared yet throw a
ReferenceError when accessed, but undeclared properties do not.
If you’d like, you can skip the
Array.prototype.push()) call to add the items to a new array, because you can get the object’s unique keys with the
Object.keys() method. That method returns an iterable that can be turned into an array with
Array.from() or the
... spread operator.
Method 3 — Finding Unique Strings with ES5
If you’re using ES5 to support older browsers like Internet Explorer 9, then you won’t have access to
Set or the
Instead, you’ll need to modify the last method to use a simple
for loop instead. The code is otherwise similar to remove duplicate strings:
Unlike the last example, there’s no easy way in ES5 to just turn the unique
Object.keys() (a method that is available in IE9) directly into an array.
You can’t use the
... spread operator or
Array.from(), so you’re required to
.push() the strings to a new array with a loop.
Set Removes Duplicate Strings
Filtering an array for unique strings requires only one line of code if you choose to use the fantastic ES6 feature
And, if you’re stuck supporting Internet Explorer, then you’ll probably not be able to use
Unique Strings from Object Values
What if you have an array of objects, and the strings you need are the values of a property on those objects — such as usernames or email addresses?
You’d need to first
Array.prototype.map()) the array, creating a new array of non-unique strings, and then apply
Set to remove the duplicates.
To learn how to use
.map() to filter the unique strings found as object values in an array of objects, please refer my complete guide to using
Happy coding! 🤩💻💯🔥🎸