JavaScript removes duplicate elements from an array
- 2020-05-16 06:23:14
- OfStack
This example shows how JavaScript removes duplicate elements from an array. Share with you for your reference. The specific analysis is as follows:
This JS code is used to remove duplicate elements from the array, such as: ['apple', 'orange', 'peach', 'apple', 'strawberry', 'orange'] deduplication and return: s ['apple', 'orange', 'peach', 'strawberry']
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 the browser
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 is helpful for you to design javascript program.