Home >Web Front-end >JS Tutorial >JavaScript method to remove duplicate elements from array_javascript skills

JavaScript method to remove duplicate elements from array_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:08:441165browse

The example in this article describes how to remove duplicate elements from an array using JavaScript. Share it with everyone for your reference. The specific analysis is as follows:

This JS code is used to remove duplicate elements from an array, such as: ['apple', 'orange', 'peach', 'apple', 'strawberry', 'orange'] Return after deduplication: s ['apple', 'orange', 'peach', 'strawberry']

Copy code 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 code below can be verified in the browser

Copy code The code is as follows:
Remove duplicate elements from an array.

 var fruits = ['apple', 'orange', 'peach', 'apple', 'strawberry', 'orange'];<br>

Note 'orange' is duplicate in fruits array. Click to remove duplicate elements from fruits array:


<script><br> function removeDuplicates(arr) {<br> var temp = {};<br> for (var i = 0; i < arr.length; i )<br />          temp[arr[i]] = true;<br /> var r = [];<br /> for (var k in temp)<br />          r.push(k);<br /> Return r;<br /> }<br /> function check() {<br /> var fruits = ['apple', 'orange', 'peach', 'apple', 'strawberry', 'orange'];<br /> var uniquefruits = removeDuplicates(fruits);<br /> alert(uniquefruits);<br /> }<br /> </script>

I hope this article will be helpful to everyone’s JavaScript programming design.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn