Home > Web Front-end > JS Tutorial > How to delete the same elements from a javascript array

How to delete the same elements from a javascript array

醉折花枝作酒筹
Release: 2021-07-20 11:17:35
Original
3950 people have browsed it

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.

How to delete the same elements from a javascript array

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 = [&#39;qiang&#39;,&#39;ming&#39;,&#39;tao&#39;,&#39;li&#39;,&#39;liang&#39;,&#39;you&#39;,&#39;qiang&#39;,&#39;tao&#39;];
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>
Copy after login

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 = [&#39;qiang&#39;,&#39;ming&#39;,&#39;tao&#39;,&#39;li&#39;,&#39;liang&#39;,&#39;you&#39;,&#39;qiang&#39;,&#39;tao&#39;];
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>
Copy after login

【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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template