1. If no method is used, the initial wording should be:
function Unique (arr) { var res=[]; for (Var i=0,len=arr.length;i<len;i++) { var obj = arr[i]; for (var J=0,jlen = res.length;j<jlen;j++) { if (res[j]===obj) break; } if (jlen===j) Res.push (obj); } return res;} var arr=[1,1, ' 2 ', ' 1 ', 3,4]arr = unique (arr); Console.log (arr);
2. If compatibility is not considered, the indexof () method of the array inside the ES5 is used.
function Unique (arr) { var res =[]; for (Var i=0,len=arr.length;i<len;i++) { var obj = arr[i]; if (Res.indexof (obj) ===-1) res.push (obj); } return res;} var arr=[1,1, ' 2 ', ' 1 ', 3,4]arr = unique (arr); Console.log (arr);//Arr=[1, ' 2 ', ' 1 ', 3,4]
3. Using filter filtering in the ES5 array:
function Unique (a) { var res = a.filter (function (item, index, array) { return Array.indexof (item) = = = Index;
}); return res;}
Method Two
The first method is to compare the elements in the original array with the elements in the result array, and we can change the idea of putting the last element of the repeating element in the original array into the result array.
function Unique (a) {
var res = [];
for (var i = 0, len = a.length; i < Len; i++) {
for (var j = i + 1; j < Len; J + +) {
This is a very clever step.
If the same element is found
Then I self-increment into the next cycle comparison
if (a[i] = = = A[j])
j = ++i;
}
Res.push (A[i]);
}
return res;
}
var a = [1, 1, ' 1 ', ' 2 ', 1];
var ans = unique (a);
Console.log (ANS); = = ["1", "2", 1]
Although the complexity is still O (n^2), but you can see the result is different, 1 appears at the end of the array, because the result array takes the last occurrence of the element position.
Method Three (sort)
If the written interview only answer the above O (n^2) plan, may not be satisfied with the interviewer, the following is a few advanced programs.
After the array is sorted by sort, the same elements are theoretically placed in the adjacent position, then the elements in the front and back positions can be compared.
function Unique (a) {
Return A.concat (). Sort (). filter (Function (item, POS, ary) {
return!pos | | Item! = Ary[pos-1];
});
}
var a = [1, 1, 3, 2, 1, 2, 4];
var ans = unique (a);
Console.log (ANS); = = [1, 2, 3, 4]
But again, 1 and "1" will be lined up, and the different objects will be lined up, because their toString () will result in the same error:
var a = [1, 1, 3, 2, 1, 2, 4, ' 1 '];
var ans = unique (a);
Console.log (ANS); = = [1, 2, 3, 4]
Of course you can write this comparison function for the different types that might appear in the array. But it seems a bit troublesome.
Method Four (object)
The object object in JavaScript is used as a hash table, which is the solution of a written test several years ago, and like sort, you can go to an array that consists entirely of number primitive types.
function Unique (a) {
var seen = {};
Return A.filter (function (item) {
return Seen.hasownproperty (item)? False: (Seen[item] = true);
});
}
var a = [1, 1, 3, 2, 1, 2, 4];
var ans = unique (a);
Console.log (ANS); = = [1, 3, 2, 4]
is still the same as the method three, because the key value of Object is a String type, so for 1 and "1" cannot be different, we can slightly improve, the type is also stored in key.
function Unique (a) {
var ret = [];
var hash = {};
for (var i = 0, len = a.length; i < Len; i++) {
var item = A[i];
var key = typeof (item) + Item;
if (Hash[key]!== 1) {
Ret.push (item);
Hash[key] = 1;
}
}
return ret;
}
var a = [1, 1, 3, 2, ' 4 ', 1, 2, 4, ' 1 '];
var ans = unique (a);
Console.log (ANS); = = [1, 3, 2, "4", 4, "1"]
While solving the annoying 1 and "1" problems, there are other problems!
var a = [{name: ' Hanzichi '}, {age:30}, new String (1), new number (1)];
var ans = unique (a);
Console.log (ANS); = = [Object, String]
But if the array elements are all number values of the underlying type, the key-value pair method should be the most efficient!
Method Five (ES6)
ES6 deployed Set and Array.from method, too powerful! If the browser supports this, you can do so:
function Unique (a) {
Return Array.from (New Set (a));
}
var a = [{name: ' Hanzichi '}, {age:30}, new String (1), new number (1)];
var ans = unique (a);
Console.log (ANS); = = [Object, object, String, number]
_.unique
Finally, let's take a look at the implementation of underscore, underscore this encapsulation into the _.unique method, called _.unique (array, [issorted], [iteratee]). Where the first parameter is required, is the need to go to the heavy array, the second parameter is optional, if the array is ordered, you can pass in the Boolean value True, the third parameter is optional, if you need the result of an array iteration to go heavy, you can pass in an iterative function. and the array element de-weight is based on the = = = operator.
In fact, it is very simple, the implementation in underscore and the above method is similar.
Let's look at its core code:
for (var i = 0, length = getlength (array); I length; i++) {
var value = Array[i],
If an iteration function is specified
Iterates over each element of an array
computed = Iteratee? Iteratee (value, I, array): value;
If it is an ordered array, the current element can only be compared with the previous element
Save the previous element with the seen variable
if (issorted) {
If i = = 0, the Direct push
Otherwise, compare whether the current element is equal to the previous element
if (!i | | seen!== computed) Result.push (value);
Seen saves the current element for the next comparison
seen = computed;
} else if (iteratee) {
If the element value is not computed in seen[]
if (!_.contains (seen, computed)) {
Seen.push (computed);
Result.push (value);
}
} else if (!_.contains (result, value)) {
If you don't have to go through an iterative function, you don't have to seen[] variables.
Result.push (value);
}
}
The outer loop iterates through the array elements, and for each element, if the array is ordered, it is compared to the previous element, and if it is the same, it has already occurred and is not added to the result array, otherwise it is added. In the case of an iterative function, the value of the incoming iteration function is computed, the value is de-weighed, and the. Contains method is called, and the core of the method is called. The IndexOf method is the same as the method we said above.
JS Array de-weight