Because the indexOf method will return the first instance the value appears, we can detect if a value is a duplicate because it will return an earlier index, instead of the one we're currently on.
When this happens, we reject this value and return false.
In the end, you're left with an array of only unique values.
Conclusion
In this post, we looked at the two best ways to remove duplicates from an array in JavaScript.
You can either use a set and initialize it with the entire array, or use the filter method to remove duplicates.
Thanks for reading and happy coding!
To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!