Home > Web Front-end > JS Tutorial > How to remove duplicate values ​​from a string in javascript

How to remove duplicate values ​​from a string in javascript

藏色散人
Release: 2021-07-13 15:54:52
Original
2712 people have browsed it

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.

How to remove duplicate values ​​from a string in javascript

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(&#39;abdacda&#39;));
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>
Copy after login

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);
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template