Home  >  Article  >  Web Front-end  >  Three JS ways to determine whether an array has duplicate values

Three JS ways to determine whether an array has duplicate values

零到壹度
零到壹度Original
2018-03-22 17:16:334796browse

This article mainly brings you three JS methods to determine whether an array has duplicate values. It is mainly shared with you in the form of code. Students in need can learn from it. I hope it can help everyone.

Method one:

var s = ary.join(",")+",";
for(var i=0;i<ary.length;i++) {
if(s.replace(ary[i]+",","").indexOf(ary[i]+",")>-1) {
alert("数组中有重复元素:" + ary[i]);
break;
}
}


Method two:

var ary = new Array("111","22","33","111");
var nary=ary.sort();
for(var i=0;i<ary.length;i++){
if (nary[i]==nary[i+1]){
alert("数组重复内容:"+nary[i]);
}
}


Method 3:

function isRepeat(arr){
var hash = {};
for(var i in arr) {
if(hash[arr[i]])
return true;
hash[arr[i]] = true;
}
return false;
}

Related links:

js determines whether the array has duplicate values

determines whether the array elements are duplicates

The above is the detailed content of Three JS ways to determine whether an array has duplicate values. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn