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.