Method: 1. Traverse the array to be deleted, put the elements into another array, and only allow the element to be put into the array if it is judged that it does not exist; 2. Put the element value and key of the target array By swapping positions, duplicate elements are automatically deleted.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
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: Automatically swap the element values and key positions of the target array arr The duplicate elements have been deleted, and the replacement looks 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>
【Recommended Learning :javascript advanced tutorial】
The above is the detailed content of How to delete the same elements from a javascript array. For more information, please follow other related articles on the PHP Chinese website!