See the Pen JavaScript - Find duplicate values in a array - array-ex- 20 by w3resource (@w3resource) on CodePen. Show Improve this sample solution and post your code through Disqus Previous: write a JavaScript program to compute the sum of each individual index value from the given arrays. What is the difficulty level of this exercise? Easy Medium HardTest your Programming skills with w3resource's quiz. Follow us on Facebook and Twitter for latest update. JavaScript: Tips of the DaySort Number Arrays JavaScript arrays come with a built-in sort method. This sort method converts the array elements into strings and performs a lexicographical sort on it by default. This can cause issues when sorting number arrays. Hence here is a simple solution to overcome this problem. [0,10,4,9,123,54,1].sort((a,b) => a-b); >>> [0, 1, 4, 9, 10, 54, 123] You are providing a function to compare two elements in the number array to the sort method. This function helps us the receive the correct output. In this tutorial I will show you how you can check if an Let's start with the data that will use in both examples:
Option 1: Check if an Array contains duplicate elementsThis is the easier of those two methods that I will talk about in this tutorial, and in fact, it is basically a one liner logic wise.
If you run the above code, you should have the following output:
This function is pretty straightforward, but I will give a quick rundown. Basically what this function does is it takes in an array. It will then initialise a 0. If the Set has fewer elements, we know that the input array contains duplicate elements.Option 2: Find and return duplicate Array elementsThe following method is more complicated than option 1, however, it is doing more than just returning whether or not an array contains duplicates as it will also return the duplicate values. Take a look at the following code:
If you run the above function, you should get the following output:
What is happening here? We initialise two After that, we loop through the 5 array that was passed to our function. When looping, it will check if the 6 Set contains the current 8, if the Set does contain the 8 then it will add that 8 to the 2 Set , if 6 does not contain the 8, then 8 gets added to 6At the end of this function we return the 2 Set which will contain all the duplicate values.Bonus: Remove duplicate elements from ArrayAnother great use of To do this, all we need to do is the following:
While this is powerful, I am not a fan of using this. I find it to be a bit messy. If I did need this, I would put it in a function just so that it would be cleaner to use. ConclusionFinding out whether an Array contains duplicates is super easy when using 4 function could be much faster than the 5 function on the Array data type, depending on the amount of data you have.If you found this article helpful, please consider sharing it with others that might also find it helpful. |