Js in the array to remove duplicate elements to retain a of two implementation ideas

  • 2020-03-30 03:43:56
  • OfStack

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

The first is: Iterate over the array arr to be deleted, placing the elements into another array TMP, and allowing them into TMP only after determining that the element does not exist in arr

Use two functions: for... In and indexOf ()


<script type="text/javascript"> 
var student = ['qiang','ming','tao','li','liang','you','qiang','tao'];
function unique(arr){
//Traversing arr, putting the elements into the TMP array (only if they don't exist)
var tmp = new Array();
for(var i in arr){
//The element does not exist inside the TMP to allow appending
if(tmp.indexOf(arr[i])==-1){
tmp.push(arr[i]);
}
}
return tmp;
}

</script>

The second way is: Transposing the arr values and key positions automatically removes the duplicate elements. 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;
}
//I'm going to switch the keys and the values again
var tmparr = new Array();

for(var n in tmp){
tmparr.push(n);
}
return tmparr;
}
</script>

Related articles: