Copy codeThe Code is as follows:
Question: Write a function to remove the repeated values in the given array.
For example:
Input array a = [0, 8, 5, 4, 78, 8, 90, 4, 'A', 'B', 'a'];
Returned results: [, a, B]
I think about this question many times after the interview, but I have never been able to come up with a method with low time complexity. Yesterday afternoon, I saw a piece of code in a book in the dormitory reading "JavaScript language essence", so I tested it on jsfiddle and succeeded. The Code is as follows (for the full version, see jsfiddle)
Copy codeThe Code is 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;
};
Summarize my ideas:
Train of Thought 1: sort the target array and then delete the repeated array in sequence. However, deleting the repeated elements also changes the attributes of the original elements of the array, which obviously does not meet the requirements, del.
Idea 2: Create an array B and push the element a to B, but check whether the element exists before push. The time complexity is n * n, which is the simplest and most stupid method.
Idea 3: similar to idea 2, but it makes full use of the attributes of the js object to create an empty object and add the elements in a as attributes to the object, check whether the property already exists before adding the property. After adding all the attributes of the object, put the attributes of the object in the array in sequence, return
The interview questions of Meituan have a variant of this question:
You must add a method to the Array class. After calling this method for any Array, you can remove repeated elements from the Array.
This variant has more knowledge points, including prototype and understanding of this.