Explained in another way, what we will do is:
- Eliminate repeating objects, either based on a property or by comparing them in depth. Let's go there.
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.
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: