All four methods need to use a temporary array and eventually return the temporary array.
(i) Use method indexof to determine whether the current element already exists in a temporary array, or push to a temporary array if it does not exist (the result returns-1).
function RemoveDuplicatedItem1 (arr) {
var retarr=[];
for (Var i=0;i<arr.length;i++) {
if (Retarr.indexof (arr[i)) ===-1) {//=== Determines whether the value is exactly the same as the type, and if the type is different, the element
is different Retarr.push (Arr[i]);
}
return retarr;
}
(b) using the uniqueness of the attribute of the object, the element of the array as the property of an object that is temporarily created, and if it does not exist, push
A temporary object created by function removeDuplicatedItem2 (arr) {
var temp={};//to store an array element as its property
var retarr=[];
for (Var i=0;i<arr.length;i++) {
if (!temp[arr[i]]) {//To determine whether the property exists, and of course it can be judged whether the current property equals 1
temp[arr[i]]=1;// Assign a value to the current property value to avoid an empty
Retarr.push (Arr[i]);
}
return retarr;
}
(iii) using a combination of foreach and indexof to determine whether the subscript of the current element is consistent with the result returned by IndexOf, and if it is consistent that the current element appears for the first time, push into a temporary array
function RemoveDuplicatedItem3 (arr) {
var retarr=[];
Arr.foreach (function (item,i,ar) {
if (Arr.indexof (item) ==i) {//To determine whether the current element is the first occurrence of
retarr.push (item);
}
);
return retarr;
}
(d) Sorting the original array, you can use sort, because only the same elements are brought together and are not required for collation. With a temporary variable temp stores the item that is currently pushed into the temporary array, and the array pointer moves back, and if the item that the pointer refers to is not equal to temp, push to the temporary array, otherwise the pointer moves back until the original array ends.
The function removeDuplicatedItem4 (arr) {
if (arr.length<=0) {//) determines in advance whether there are elements in the array to prevent the array from being out of bounds
return-1;
}
var retarr=[];
Arr.sort ();
The Var nowitem=arr[0];//initial value stores the first element in the original array
Retarr.push (nowitem);
for (Var i=1;i<arr.length;i++) {
if (arr[i]!=nowitem) {
retarr.push (arr[i]);
nowitem=arr[i];//change the value of Nowitem} return
Retarr;
}
References: http://www.cnblogs.com/leonwang/p/4845576.html