javascript - Determining whether an array contains duplicate values -


i scan through js array , determine if elements unique, or whether array contains duplicates.

example :

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

i want result :

my_array1 must return true, because array element unique , array2 must return false, because array element not unique 

how can go writing method?

if want check uniqueness can also this.as stated on comment not assert best option.there great answers down below.

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

arr.slice(0) creates temporary copy of array, on actual processing done.this because when uniqueness criteria met clear array (b) short circuit loop.this make sure processing stops criteria met.

and more nicer if expose method on array instance. can [1,2,3,5,7].isunique();

add following snippet , ready 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


Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -