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
Prabhu murthy
source share