How to remove repeated elements in an array using JavaScript

Source: Internet
Author: User

How to remove repeated elements in an array using JavaScript

This article mainly introduces how to remove repeated elements from an array using JavaScript. The example analyzes the skills related to javascript traversal and deletion operations. For more information, see

 

 

This example describes how to remove repeated elements from an array using JavaScript. Share it with you for your reference. The specific analysis is as follows:

This JS code is used to remove repeated elements from the array, such as ['apple', 'Orange ', 'peach', 'apple', 'strawberry ', 'Orange '] After deduplication, return: s ['apple', 'Orange', 'peach ', 'strawberry']

The Code is as follows:

Function removeDuplicates (arr ){
Var temp = {};
For (var I = 0; I <arr. length; I ++)
Temp [arr [I] = true;
Var r = [];
For (var k in temp)
R. push (k );
Return r;
}
// Usage
Var fruits = ['apple', 'Orange ', 'peach', 'apple', 'strawberry ', 'Orange'];
Var uniquefruits = removeDuplicates (fruits );
// Print uniquefruits ['apple', 'Orange ', 'peach', 'strawberry '];

 

The following code can be verified in a browser:

The Code is as follows:

Remove duplicate elements from an array. <br>
<Pre> var fruits = ['apple', 'Orange ', 'peach', 'apple', 'strawberry ', 'Orange'];
</Pre>
Note 'Orange 'is duplicate in fruits array. Click to remove duplicate elements from fruits array: <br>
<Button onclick = "check ()"> Remove Duplicate </button>
<Script>
Function removeDuplicates (arr ){
Var temp = {};
For (var I = 0; I <arr. length; I ++)
Temp [arr [I] = true;
Var r = [];
For (var k in temp)
R. push (k );
Return r;
}
Function check (){
Var fruits = ['apple', 'Orange ', 'peach', 'apple', 'strawberry ', 'Orange'];
Var uniquefruits = removeDuplicates (fruits );
Alert (uniquefruits );
}
</Script>

 

I hope this article will help you design javascript programs.

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.