How to remove duplicate string values in javascript: first open the corresponding front-end code file; then use the hash function of javascript to remove duplicate string values.
The operating environment of this article: Windows 7 system, javascript1.8.5, Dell G3 computer.
How to remove duplicate values from a string in javascript?
javascript removes repeated characters in a string
In javascript, the object is actually a hash table, the attribute name is the key of the hash table, and the value of the attribute is Hash table value.
See more at http://www.nowamagic.net/librarys/veda/detail/759
Use the natural hash function of javascript
<html> <body> <script type="text/javascript"> console.log(dropRepeat('abdacda')); function dropRepeat(str){ var result=[]; var hash={}; for(var i=0, elem; i<str.length;i++){ elem=str[i]; if(!hash[elem]){ hash[elem]=true; result.push(elem); } } return result; } </script> </body> </html>
The result is ["a ", "b", "d", "c"]
There is also a calculation of the number of occurrences
var str = "dog cat dog mouse dog cat"; function getFrequence(str){ var arr = str.split(" "); var result = {}; for(var i=0, len=arr.length; i<len;i++){ if(!result[arr[i]]){ result[arr[i]] = 1; }else{ result[arr[i]] += 1; } } for(var item in result){ console.log(item + " " + result[item]); // dog 3 // cat 2 // mouse 1 } } getFrequence(str);
Related video tutorial sharing: javascript advanced video
The above is the detailed content of How to remove duplicate values from a string in javascript. For more information, please follow other related articles on the PHP Chinese website!