JS Array Remove duplicate data only one of the implementation code _javascript tips

Source: Internet
Author: User
Tags hash

Very little said, JS array to remove duplicate data from the code below:

var arr = [1,2,3,4,5,6,1,6,7,2];
var newArr = [];
for (var i =0;i<arr.length-1;i++) {
if (Newarr.indexof (arr[i)) = = 1) {
Newarr.push (arr[i]);
}
}

Here to share the high efficiency remove the JS array duplicates

The array type does not provide a way to repeat, if you want to kill the repeating elements of the array, you have to do it yourself:

function Unique (arr) {
var result = [], isrepeated;
for (var i = 0, len = arr.length i < len; i++) {
isrepeated = false;
for (var j = 0, Len = result.length J < Len; J + +) {
if (arr[i] = Result[j]) { 
isrepeated = true;
break;
}
}
if (!isrepeated) {
result.push (arr[i]);
}
return result;

The overall idea is to move the elements of the array to another array, the process of handling to check whether the element is duplicated, if there is a direct throw away. It can be seen from nested loops that this method is extremely inefficient. We can use a Hashtable structure to record existing elements so that the inner loops can be avoided. Exactly, implementing Hashtable in JavaScript is extremely simple, as follows:

function Unique (arr) {
var result = [], hash = {};
for (var i = 0, elem; (Elem = arr[i])!= null; i++) {
if (!hash[elem]) {
result.push (elem);
Hash[elem] = true;
}
}
return result;
http://www.cnblogs.com/sosoft/
}

The above is a small set to introduce the JS array to remove duplicate data only one of the implementation code, hope to help everyone, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.