SoFunction
Updated on 2025-03-10

Implementation method of removing duplicate values ​​from arrays in JavaScript

Copy the codeThe code is as follows:

Question: It is required to write a function to remove duplicate values ​​from a given array.
like:
Pass in array a = [0, 8, 5, 4, 78, 8, 90, 4, 'a', 'b', 'a'];
Required to return: [0,4,5,8,78,90,a,b]

I thought about this question many times after the interview, but I have never been able to come up with a method with a low time complexity. Yesterday afternoon, I saw a piece of code in a book triggered when I watched "JavaScript Language Essence" in the dormitory, so I tested it on jsfiddle and it was successful. The code is as follows (see jsfiddle for the full version)
Copy the 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 < ; i++) {
temp = src[i];
if (res[temp]) {
//do noting
} else {
res[temp] = 1;
}
}
for (name in res) {
if ((name)) {
curr[j++] = name;
}
}
return curr;
};

Let me summarize my ideas:
Idea 1: Sort the target array, and then delete the duplicate arrays in sequence, but this way, while deleting the duplicate elements, it also changes the properties of the original elements of the array, which is obviously not in line with the requirements, del.
Idea 2: Create a new array b, push the element in a to b, but check whether the element exists before pushing. This time complexity is n*n, the easiest and stupidest method.
Idea 3: Similar to Idea 2, but it makes full use of the properties of the js object, create a new empty object, add the element in a to the object as an attribute, and detect whether the attribute already exists before adding. After adding all the properties of the object are placed in the array in order, return
There is a variant of this question in Meituan’s interview:
It is required to add a method on the Array class, and after calling the method for any array, the duplicate elements in the array are removed.
This variant tests more knowledge points, including prototypes, this understanding, etc.