In this post, we will see how to remove duplicates from an array in JavaScript.
We will look into two methods - ES6 and Vanilla JavaScript.
The output of this code will be -
Set - lets you store unique values of any type, whether primitive values or object references.
Spread - allows an iterable to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected.
The output of this code snippet will be -
We will look into two methods - ES6 and Vanilla JavaScript.
ES6 Method
Set - lets you store unique values of any type, whether primitive values or object references.
Spread - allows an iterable to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected.
Using Vanilla JavaScript
If you want to use vanilla JavaScript, you can utilize Array.indexOf() and Array.filter() methods as follows -
But how does this work? For example, “turkey” shows up at 0, 2, and 6 index. The line
sandwiches.indexOf(sandwich)
returns the first matching index of “turkey” always, hence when the index of “turkey” is 0, it is returned but for indexes 2 and 6, the condition becomes false and hence they are ignored. This is true for all the other duplicates.
Conclusion
In this post, we discussed two approaches of removing duplicates from an array in JavaScript - ES6 and Vanilla JS.
I would love to hear your thoughts on this post and would like to have suggestions from you to make this post better.
Happy Learning 😊
Comments
Post a Comment