How to remove duplicate values from an array in JavaScript _javascript tips

Source: Internet
Author: User
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.
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.