The example summarizes several commonly used techniques for deleting duplicate elements in arrays using javascript. Friends who need it can refer to it.
Here we share a high-frequency front-end interview question, which mainly implements deleting duplicate elements from arrays using javascript. I hope it will be helpful to beginners
//数组去重的方法 Array.prototype.unique=function(){ //集中声明变量 var oldArr=this, newArr=[oldArr[0]], len=oldArr.length, i=1; //过滤空数组 if(!len) return this; //过滤重复元素 for(;i Copy after login
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 in the future. For example, it can be extended to deduplication of object elements or can operate multiple arrays at the same time. Here are a few methods written by others for comprehensive comparison.
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:
Put the element values of the target array arr and Changing the position of the key will automatically delete the duplicate elements. The result after the replacement is: array('qiang'=>1, 'ming'=>1, 'tao'=>1)
Method 4
/** * 去除数组重复元素 */ function uniqueArray(data){ data = data || []; var a = {}; for (var i=0; i Copy after login
The methods are all similar. The third method is a better idea.
The above is the detailed content of Recommended summary of several JavaScript methods to delete duplicate elements. For more information, please follow other related articles on the PHP Chinese website!