Javascript array deduplication, javascript Array

Source: Internet
Author: User
Tags javascript array

Javascript array deduplication, javascript Array

// Remove the Array of numeric elements function sortnum (a, B) {return a-B;} Array. prototype. unique1 = function () {this. sort (sortnum); var newnumbers = [this [0]; for (var I = 0; I <this. length; I ++) {if (this [I]! = Newnumbers [newnumbers. length-1]) {newnumbers. push (this [I]) ;}}; return newnumbers ;}; var mynums = [1, 2, 5, 8, 2, 5, 7, 42, 8, 0]; mynums = mynums. unique1 (); console. log (mynums); // The json object can be used to retrieve non-numeric element arrays. prototype. jsonUnique = function () {var json = {}; for (var I = 0; I <this. length; I ++) {if (! Json [this [I]) {json [this [I] = 1 ;}}; return json ;}; var mynumss = [, 54,1, 54, 'haha ', 'haha', 'ours ', 'who', 'who']; mynumss = mynumss. jsonUnique (); for (var key in mynumss) {console. log (key );}


Javascript array deduplication

Arr is an array to be duplicated, and ret is a new array obtained after deduplication. hash is equivalent to a Map to record whether an element already exists in ret.
The program traverses arr and uses the type of each element + this element as the Map key. If the key already exists in the hash, it will not be added to ret, if not, add it to ret and add the new key to hash.

If (hash [key]! = 1) Actually, it is used to determine whether the current element has appeared.

The javascript array should be de-duplicated, and should be effective for no matter how complicated the array is. Write a detailed comment and add 50 points if the answer is satisfactory.

The attributes of the Object in JS are unique. Just make good use of it.
Only one row of country input is valid.

The uniqueness in city is unknown and needs to be treated separately, but it can be processed by name or value,
You must specify one. Is to give your desired processing result as an example for further implementation.

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.