JavaScript removes repeated elements from the array.
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']
Copy codeThe 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:
Copy codeThe 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.