DEV Community

loading...

How to remove duplicate words from an array in JavaScript?

Murtaja Ziad
A Full-Stack Web Developer.
Originally published at blog.murtajaziad.xyz on ・1 min read

In this article, you will learn how to remove duplicate words from an array in JavaScript.

Snow Capped Mountain During Evening — Pexels

That’s the array of duplicate words that we have:

let duplicate_words = ["camera", "signature", "camera", "guitar", "guitar", "camera"];
Enter fullscreen mode Exit fullscreen mode

By default, a set cannot have duplicate elements.

So, we can remove duplicate words from an array by converting it to a set.

let words_set = new Set(duplicate_words);
Enter fullscreen mode Exit fullscreen mode

If we log the set to the console, we will get:

console.log(words_set); // Set(3) {"camera", "signature", "guitar"}
Enter fullscreen mode Exit fullscreen mode

We need it as an array, so we will convert the set back to an array using the spread operator.

let words = [...words_set];
Enter fullscreen mode Exit fullscreen mode

Now, log the words to the console.

console.log(words); // ["camera", "signature", "guitar"]
Enter fullscreen mode Exit fullscreen mode

The duplicate words have been removed from the array successfully!

Follow me on Twitter, and subscribe to my YouTube channel!

Discussion (0)