Home  >  Article  >  Web Front-end  >  js deletes duplicate elements in an array and keeps one (two implementation ideas)_javascript skills

js deletes duplicate elements in an array and keeps one (two implementation ideas)_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:39:021388browse

For example: var student = ['qiang','ming','tao','li','liang','you','qiang','tao'];

The first idea is: Traverse the array arr to be deleted, put the elements into another array tmp respectively, and only after judging that the element does not exist in arr can it be put into tmp

Two functions are used: for ...in and indexOf()

<script type="text/javascript"> 
var student = ['qiang','ming','tao','li','liang','you','qiang','tao'];
function unique(arr){
// 遍历arr,把元素分别放入tmp数组(不存在才放)
var tmp = new Array();
for(var i in arr){
//该元素在tmp内部不存在才允许追加
if(tmp.indexOf(arr[i])==-1){
tmp.push(arr[i]);
}
}
return tmp;
}

</script>

The second idea is: Swapping the element values ​​and key positions of the target array arr will automatically delete the duplicate elements. The swap will look like: array('qiang'=> ;1,'ming'=>1,'tao'=>1)

<script type="text/javascript">
var student = ['qiang','ming','tao','li','liang','you','qiang','tao'];
function unique(arr){
var tmp = new Array();

for(var m in arr){
tmp[arr[m]]=1;
}
//再把键和值的位置再次调换
var tmparr = new Array();

for(var n in tmp){
tmparr.push(n);
}
return tmparr;
}
</script>
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