if you are worried because performance, you might want to check this out:
function isOnce(itm,arr){
var first_match=-1;
for(var i=0,len=arr.length;i<len;i++){
if(arr[i]===itm){
first_match=i;
break;
}
}
if(first_match!=-1){
var last_match=-1;
for(i=arr.length-1;i>first_match;i--){
if(arr[i]===itm){
last_match=i;
break;
}
}
if(last_match==-1){
return true;
}
}
return false;
}
You will notice savings when these two points met:
- There are 2 or more matches
- The first and last match are at least 1 space apart
In other words, you don't ever loop on the elements that are between first and last match. So the best case scenario would be:
arr=["a", ...(thousands of items here)... ,"a"];// you only looped 2 times!