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.
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>
Before removing : John,Ram,Rahim,Remo,Ram,Rahim After using set() method : John,Ram,Rahim,Remo
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.
<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>
Before removing : John,Ram,Rahim,Remo,Ram,Rahim After filter() method : John,Ram,Rahim,Remo
- Related Articles
- Find All Duplicates in an Array in C++
- Find Duplicates of array using bit array in Python
- Find Duplicates of array using bit array in C++
- How to filter an array in Java