JavaScript arrays are one of the most popular data structures used by web developers all over the world. They are very powerful and offer tons of features. While working with arrays, mostly, people need to remove duplicates from an array. But sometimes you may want to retrieve the duplicate values in JS array. In this article, we will learn how to get duplicate values in JS array.
How to Get Duplicate Values in JS Array
We will learn how to get non unique values in JavaScript array. For this purpose, we will write a custom function.
function findDuplicates(arr){ var sorted_arr = arr.slice().sort(); var results = []; for (let i = 0; i < sorted_arr.length - 1; i++) { if (sorted_arr[i + 1] == sorted_arr[i]) { results.push(sorted_arr[i]); } } return results; } var duplicatedArray = [8, 8, 11, 2, 3, 5, 5, 5, 7]; console.log(findDuplicates(duplicatedArray)); // [8,5,5]
Let us look at the above in detail. First, we sort the input array using sort() function which is available by default for every JS array. We have used the default sorting mechanism. If you want to customize sorting, you can define your sorting function within sort(function(a,b){…}).
Next, we loop through the sorted array. In each iteration, we determine if the current element is a duplicate or not. If so, we push it into results array. Finally, when the original array is looped through, we will have all the duplicate elements in results array.
If you already have a sorted array, you can skip the sorting part and directly extract the duplicate elements.
The above code will contain each duplicate copy of non unique elements. If you only want a single copy of each non unique element, you can convert the results array into a set, which will drop duplicates and then convert it back into an array.
var set = Set.new(results); // (8,5,5) var new_result = Array.from(set); // [8,5]
In this article, we have learnt how to get duplicate values in JS array. You can use it to get non unique values in JS array.
Also read:
How to Create Multiline Strings in JavaScript
How to Split String By Particular Character
How to Read Local Text File in Browser Using JavaScript
How to Encode String to Base64 in JavaScript
How to Get Length of JavaScript Object
Related posts:
Sreeram has more than 10 years of experience in web development, Python, Linux, SQL and database programming.