Home >Web Front-end >JS Tutorial >How to remove duplicate values ​​from an array in JavaScript_javascript skills

How to remove duplicate values ​​from an array in JavaScript_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:04:01901browse
Copy code The code is as follows:

Question: Asked to write a function to remove duplicate values ​​from a given array .
For example:
Pass in array a = [0, 8, 5, 4, 78, 8, 90, 4, 'a', 'b', 'a'];
Required 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 solution with lower time complexity. method. Yesterday afternoon I was reading "The Essence of JavaScript Language" in my dormitory and saw a code in a book that triggered something, so I tested it on jsfiddle and it was successful. The code is as follows (see jsfiddle for the complete version)
Copy code The 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;
};

To summarize my ideas:
Idea 1: Sort the target array, and then in order Delete duplicate arrays, but this will not only delete duplicate elements but also change the attributes of the original elements of the array, which is obviously not in compliance with the requirements, del.
Idea 2: Create a new array b, push the elements in a to b, but check whether the element exists before pushing. This time complexity is n*n, which is the simplest and stupidest method.
Idea three: Similar to idea two, but making full use of the properties of the js object, creating a new empty object, adding the elements in a as attributes to the object, and checking whether the attribute already exists before adding it. After all are added, put the properties of the object into the array in order, return
There is a variant of this question in the Meituan interview question:
It is required to add a method to the Array class, and call this method for any array. method, remove duplicate elements from the array.
This variant question tests more knowledge points, including prototypes, understanding of this, etc.
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn