Home > Web Front-end > JS Tutorial > body text

js method to count the number of occurrences of characters and remove duplicates

王林
Release: 2020-05-08 09:16:12
forward
2466 people have browsed it

js method to count the number of occurrences of characters and remove duplicates

Code sample:

var str = "aabbccehgfhaasdhgfashdfhabcasd";

    // 使结果显示为一个对象,如:{a:2, b:1, c:2, d:1}

    var obj = {};

    // console.log(obj[ "a" ])     // undefined

    // obj[ "a" ] = 1
    // obj[ "a" ] ++

    // obj[ "b" ] = 1
    // obj[ "b" ] ++
    // obj[ "b" ] ++
    // obj[ "b" ] ++

    // obj[ "c" ] = 1

    for(var i=0;i<str.length;i++){
        // obj[ str[i] ]
        if(obj[ str[i] ]){
            obj[ str[i] ]++;
        }else{
            obj[ str[i] ] = 1;
        }
    }
    console.log(obj);


    var newStr = "";
    for(var key in obj){
        newStr += key;
    }
    console.log(newStr);
Copy after login

Recommended tutorial: js entry tutorial

The above is the detailed content of js method to count the number of occurrences of characters and remove duplicates. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:cnblogs.com
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