Deduplicate an array of strings or numbers
To remove duplicates in an array of primitive values, such as string or number, you can convert it into a Set and convert it back into an array:
This works because the
Set can only contain unique values. However, it will not work with more complex values such as objects.
Remove duplicates from an array of objects
id. Then you can store those ids in an object, as you filter the array, and if there's already an id stored, skip the element.
Here's a function to deduplicate an array of objects:
The function accepts a
getKey function to get a unique string key for each array item. That key will then be used to check uniqueness.
Here's how to use it:
Find this and more code examples in my GitHub repository.