Table of Contents
- Using the indexOf() method
- Using the has() method
- Using an object & key value pairs
- Using the "some" function
- Using iteration
- Other Related Concepts
Using the indexOf() method
In this method, what we do is that we compare the index of all the items of an array with the index of the first time that number occurs. If they don’t match, that implies that the element is a duplicate.All such elements are returned in a separate array using the filter() method.
Using the has() methodIn the above implementation, the output array can have duplicate elements if the elements have occurred more than twice in an array. To avoid this and for us to count the number of elements duplicated, we can make use of the use() method.
The above solution finds and returns the duplicate elements using the has() method. This works more efficiently than the previous method because each value in the Set has to be unique.
This can be used when you are concerned which exact elements have duplicates
In the argument callback function, we obtain the current array element as the first argument and the index of current element as the second argument.
We can then compare the current element’s index to the index of the first element with the same value. If both the indices are the same, that implies that there are no duplicate elements.