The examples in this article describe the way JavaScript deletes an array of repeating elements. Share to everyone for your reference. The specific analysis is as follows:
Here to share a front-end interview high-frequency problem, the main implementation of JavaScript delete array repeating elements. Hope to help beginners
The method of array
array.prototype.unique=function () {
//Set declared variable
var
oldarr=this,
Newarr=[oldarr[0]],
len=oldarr.length,
i=1;
Filter empty array
if (!len) return this;
Filter repeating element for
(; i<len;i++) {
newarr.indexof (oldarr[i]) <0? Newarr.push (_this): ';
}
Returns filtered array does not affect the original array return
NEWARR;
}
var arr=[' A ', ' a ', ' B ', ' A ', ' C ', ' d '];
Console.log (Arr.unique ());
["A", "B", "C", "D", Unique:function]
Although there are a lot of online and their own writing is not very good, but after all, the logic of their own writing can also follow the logical extension such as extension to the object elements to the weight or can be operated at the same time multiple arrays and so on here and then put others to write several methods can be combined to compare
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:
Iterates through the array arr to be deleted, placing the elements in another array tmp, allowing the element to be placed in TMP if it is not present in ARR
Use two functions: for ... in and IndexOf ()
var student = [' Qiang ', ' Ming ', ' Tao ', ' Li ', ' Liang ', ' You ', ' Qiang ', ' Tao '];
function Unique (arr) {
//traversal arr, putting elements into the TMP array (not present)
var tmp = new Array ();
for (var i in arr) {
//The element does not exist inside TMP to allow append
if (Tmp.indexof (arr[i)) ==-1) {
}
} return
tmp;
}
Method 3:
Replace the element value of the target array arr with the position of the key to automatically delete the duplicated elements, and replace them like this: 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
}
Again, the position of the key and the value is replaced by the
var Tmparr = new Array ();
for (var n in tmp) {
tmparr.push (n);
}
return tmparr;
}
</script>
Method 4
/**
* Remove Array repeat element
*
/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 method is almost the third way. The idea is quite clever.
I hope this article will help you with your JavaScript programming.