Home >Web Front-end >JS Tutorial >Summary of methods for deleting duplicate elements from arrays in javascript_javascript skills
The example in this article describes how to delete duplicate elements from an array using JavaScript. Share it with everyone for your reference. The specific analysis is as follows:
Here I share a frequently asked front-end interview question, which mainly implements javascript to delete duplicate elements in an array. Hope it helps for beginners
//数组去重的方法 Array.prototype.unique=function(){ //集中声明变量 var oldArr=this, newArr=[oldArr[0]], len=oldArr.length, i=1; //过滤空数组 if(!len) return this; //过滤重复元素 for(;i<len;i++){ newArr.indexOf(oldArr[i])<0 ? newArr.push(_this) : ''; } //返回过滤后的数组没有影响原数组 return newArr; } var arr=['a','a','b','a','c','d']; console.log(arr.unique()); //["a", "b", "c", "d", unique: function]
Although there are many on the Internet and the ones I wrote are not very good, after all, the logic I wrote is clear and can be expanded along the logic, such as extending to object elements to remove duplicates or operating multiple arrays at the same time, etc. I will put them here. You can comprehensively compare several methods written by others
Method 1:
function oSort(arr) { var result ={}; var newArr=[]; for(var i=0;i { if(!result[arr[i]]) { newArr.push(arr[i]) result[arr[i]]=1 } } return newArr }
Method 2:
Traverse the array arr to be deleted, and put the elements into another array tmp respectively. Only after judging that the element does not exist in arr can it be placed into tmp
Two functions are used: for ...in and indexOf()
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){ } } return tmp; }
Method 3:
Swapping the element values and key positions of the target array arr will automatically delete 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>
Method 4
/** * 去除数组重复元素 */ function uniqueArray(data){ data = data || []; var a = {}; for (var i=0; i<data.length; i++) { var v = data[i]; if (typeof(a[v]) == 'undefined'){ a[v] = 1; } }; data.length=0; for (var i in a){ data[data.length] = i; } return data; }
The methods are similar, but the third method is quite clever~
I hope this article will be helpful to everyone’s JavaScript programming design.