Copy Code code as follows:
Topic: Write a function that removes duplicate values from the given array.
Such as:
Incoming array A = [0, 8, 5, 4, M, 8, N, 4, ' A ', ' B ', ' a '];
Request return: [0,4,5,8,78,90,a,b]
For this topic, after the interview also thought several times, but has not been able to come up with a less time complexity of the method. Yesterday afternoon in the dormitory to see "The JavaScript language pristine" saw a book in a piece of code triggered, so on the Jsfiddle test, success. The code is as follows (full version see JSFIDDLE)
Copy Code code as follows:
var getnr = function (src) {
src = src | | [];
var res = {};
var curr = [];
var i, j = 0,temp, name;
for (i = 0; i < src.length; i++) {
temp = Src[i];
if (Res[temp]) {
Do noting
} else {
Res[temp] = 1;
}
}
for (name in res) {
if (Res.hasownproperty (name)) {
curr[j++] = name;
}
}
return curr;
};
To sum up my thinking:
Idea one: Sort the target array, and then delete the duplicate array in order, but this will also change the attributes of the original elements of the array while deleting the duplicate elements, Del.
Idea two: Create an array b, push the elements in a to B, but check that the element exists before the push. This time complexity is n*n, the simplest is the most stupid way.
Train of thought three: similar to train of thought, but make full use of the properties of the JS object, create a new empty object, add the element in a as a property to the object, and detect whether the property already exists before adding it. When you are finished adding all the properties of the object to the array, return
There is a variant of this topic in the interview with the American group:
Requires that you add a method to the array class, and then, after calling the method on any array, remove the repeating elements from the array.
This variant examines more knowledge, including prototypes, this understanding, and so on.