Determining if an array contains duplicate values

I would like to scan the JS array and determine if all elements are unique or the array contains duplicates.

example:

my_array1 = [1, 2, 3] my_array2 = [1, 1, 1] 

I want to get the result as follows:

 my_array1 must be return true, because this array element is unique and array2 must be return false, because this array element is not unique 

How can I write this method?

+7
javascript jquery arrays
source share
9 answers

if you want to test uniqueness, you can also do this. As stated in the comment, I am not saying that this is the only best option. Below are some great answers.

 var arr = [2,3,4,6,7,8,9]; var uniq = []; // we will use this to store the unique numbers found // in the process for doing the comparison var result = arr.slice(0).every(function(item, index, array){ if(uniq.indexOf(item) > -1){ // short circuit the loop array.length=0; //(B) return false; }else{ uniq.push(item); return true; } }); result --> true 

arr.slice(0) creates a temporary copy of the array on which the actual processing is performed. This is because when the matching criteria is unique, I clear array (B) to shorten the loop. This will ensure that processing stops as soon as the criteria are met.

And it would be better if we consider this as an instance method of an array. so we can do something like this [1,2,3,5,7].isUnique();

Add the following snippet and you are ready to go

 Array.prototype.isUnique = function() { var uniq = []; var result = this.slice(0).every(function(item, index, arr) { if (uniq.indexOf(item) > -1) { arr.length = 0; return false; } else { uniq.push(item); return true; } }); return result; }; arr.isUnique() --> true 

Demo

+2
source share

Sort your array first, and then go on to a simple comparison loop.

 function checkIfArrayIsUnique(arr) { var myArray = arr.sort(); for (var i = 0; i < myArray.length; i++) { if (myArray.indexOf(myArray[i]) !== myArray.lastIndexOf(myArray[i])) { return false; } } return true; } 
+3
source share

try the following: -

 var my_array1 = [1, 2, 3] var my_array2 = [1, 1, 1] function isUnique(obj) { var unique=obj.filter(function(itm,i,a){ return i==a.indexOf(itm); }); return unique.length == obj.length; } alert(isUnique(my_array1)) alert(isUnique(my_array2)) 

Demo

+2
source share

You can try the following:

 function uniqueArray(arr) { var hash = {}, result = []; for ( var i = 0, l = arr.length; i < l; ++i ) { if ( !hash.hasOwnProperty(arr[i]) ) { hash[ arr[i] ] = true; result.push(arr[i]); } } return result; } 
+2
source share

I think you can try Underscore js , a powerful javascript library

Underline example

 function checkUniqueArr(arr){ var unique_arr = _.uniq(arr); return arr.length == unique_arr.length; } 
+1
source share

The most effective way to verify uniqueness:

 function isUnique(arr) { for(var i = 0; i < arr.length; i++) { if (arr.indexOf(arr[i]) != i) return false; } return true; } 

In the worst case, this is O(n2) . In most cases, it is not necessary to complete the scan of a non-standard array.

+1
source share
 function containsDuplicates(arr) { var seen = {}; var duplicate = false; for (var i = 0; i < arr.length; i++) { if (seen[arr[i]]) { duplicate = true; break; } seen[arr[i]] = true; } return duplicate; } 

jsFiddle

Best case: O(1) time and space - the second element is a duplicate
Medium / Worse: O(n) time and space - no duplicates, or the duplicate is in the middle

Many of the answers here seem to rely on some complicated interpolation of array methods, which are essentially iterative and usually don't seem suitable for this rather simple task. Algorithmically, this problem can be solved in O(n) time, but any embedding of indexOf / filter / map (or similar array methods) in a for loop means that your calculation time will grow (at best) quadratically with the size of your array, and not linear. It is inefficient in time.

Now, in general, micro-optimization is really not needed if you have not identified it as a performance bottleneck in your application. But such an algorithm, in my opinion, is what you develop (in pseudo-code) and meet the requirements of your application before you start coding. If you have a huge data set in your array, you will probably appreciate the opportunity not to look at it several times to get an answer. Of course, the caveat here is that you are wasting time on the complexity of the space, since my solution requires O(n) space to cache the previously seen values.

+1
source share
 If you need to check all element are unique then following will do the trick <script> my_array1 = [11, 20, 3] my_array2 = [11, 11, 11] var sorted1= my_array1.sort(); var sorted2= my_array2.sort(); if(sorted1[0]==sorted1[sorted1.length-1]) alert('all same'); if(sorted2[0]==sorted2[sorted2.length-1]) alert('all same'); </script> 
0
source share

I just came up with this answer. I'm getting ready for an interview. I think it's rock solid.

 let r = [1,9,2,3,8]; let r2 = [9,3,6,3,8]; let isThereDuplicates= r.slice().sort().some((item,index,ar)=>(item ===ar[index+1])); console.log('r is: ',isThereDuplicates) // -> false. All numbers are unique isThereDuplicates= r2.slice().sort().some((item,index,ar)=>(item ===ar[index+1])); console.log('r2 is: ',isThereDuplicates) //->true. 3 is duplicated 

I first chop and sort without changing the original array.

 r.slice().sort() 

Then I check that for at least one element, the element is equal to the next element in the array.

 .some((item,index,array)=> item === array[index+1] ); 
0
source share

All Articles