We can remove duplicates from an JS array using multiple ways like set, filter and reduce JS functions.
In this article, We will demonstrate the way, We can achieve this using JS Set.
let duplicateNames = ['Jack', 'Walker', 'Snow', 'Daniel', 'Snow', 'Anne', 'Anne'] let uniqueNames = new Set(duplicateNames); // Output would be : Set {'Jack', 'Walker', 'Snow', 'Daniel', 'Anne'} let uniqueNamesArray = [..uniqueNames]; // Output would be : ['Jack', 'Walker', 'Snow', 'Daniel', 'Anne']
So in this example, We are performing two operations.
As set by default provides functionality of unique elements. First, We will convert our array which contains duplicate names into Set. then once you have set you can convert it using spread operator to Array.
Set:
Set
objects are collections of values. You can iterate through the elements of a set in insertion order. A value in the Set
may only occur once; it is unique in the Set
‘s collection. (Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set)
ES6 provides Arrays additional power using from function where you can convert set to an array.
Let’s do the above operation with Arrays’ from function.
let duplicateNames = ['Jack', 'Walker', 'Snow', 'Daniel', 'Snow', 'Anne', 'Anne'] let uniqueNamesArray = Arrays.from(new Set(duplicateNames)); // Output would be : ['Jack', 'Walker', 'Snow', 'Daniel', 'Anne']
This is the fastest and easiest way to remove duplicates from Arrays using native javascript of ES6.
Let us know your feedback in the comment.