Removing duplicates
To remove duplicates in an array we have many logical methods, but advanced javascript has provided some methods so that the task of removing duplicates has become very simple. Some of those methods are set() and filter(). For better understanding lets' discuss each method individually.
Set()
The important use of the set() method is that it only allows unique values. In other words, it will automatically remove duplicates and makes the task easy for us. The Set() method won't take any logical approach in removing duplicates.
Example
In the following example, the duplicates in the provided array have been removed without any logical approach by using set() method.
<html> <body> <script> var dupNames = ['John', 'Ram', 'Rahim', 'Remo', 'Ram', 'Rahim']; var uniArr = [...new Set(dupNames)]; document.write("Before removing :" +" "+ dupNames); document.write("</br>"); document.write("After using set() method :" +" "+ uniArr); </script> </body> </html>
Output
Before removing : John,Ram,Rahim,Remo,Ram,Rahim After using set() method : John,Ram,Rahim,Remo
filter()
In the following example, using filter() method each element is scrutinized whether it is repeated two or more times. If any element found repeated two or more times then only one of its value is permitted and displayed as shown in the output.
Example
<html> <body> <script> var dupnam = ['John', 'Ram', 'Rahim', 'Remo', 'Ram', 'Rahim']; var x = (dupname) => dupname.filter((v,i) => dupname.indexOf(v) === i) document.write("Before removing : " +" "+ dupname); document.write("</br>"); document.write("After filter() method :" +" "+x(dupname)); </script> </body> </html>
Output
Before removing : John,Ram,Rahim,Remo,Ram,Rahim After filter() method : John,Ram,Rahim,Remo