Home  >  Article  >  Web Front-end  >  js method to count the number of occurrences of characters and remove duplicates

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

王林
王林forward
2020-05-08 09:16:122453browse

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);

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!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete