DEV Community

joshua-brown0010
joshua-brown0010

Posted on

Remove duplicate characters in a string javascript

In this post, we will see how to remove duplicate or repeating elements from an array in JavaScript . For this, we will not limit ourselves to arrays with simple data types; but also object arrangements.

Explained in another way, what we will do is:

  • See how to remove repeated primitive data (string, integer, boolean, etc.) from arrays in JavaScript
  • Eliminate repeating objects, either based on a property or by comparing them in depth. Let's go there.

Remove array duplicates, with simple data:

Let's first see how to remove duplicates from an array but when they are not objects. There are many ways, you can use the one you want but I recommend the one that uses sets.

These methods work for strings, numbers, and Booleans.

Method 1: Filtering array

NOTE This method has better compatibility with older browsers.
The first way is by doing a filter; which filters an array and returns a new one with the elements that have passed the filter.

Knowing this, we can filter an array, on the condition that this value is not repeated in it. And how do we know if that value already exists? we use indexOf, which returns the index of the first element that matches the search in an array.

In this case, only if the current index (in the filter) is equal to the index returned by the function, we let the value pass.

Explained in other words, we only let the value pass if it is the first time it appears, if not, we discard it because it already existed previously.

The code looks like this:
Read more

Top comments (2)

Collapse
 
muttsuri profile image
Muttsuri

Couldn't we just pass the array to a Set() and then back to an array?

Collapse
 
calag4n profile image
calag4n

I'd do this way