UnderScore.js統計字符出現頻率

//方法一
var words = 'Also known as inject and foldl reduce boils down a list of values into a single value.' +

' Memo is the initial state of the reduction, and each successive step of it should be ' +

'returned by iterator. The iterator is passed four arguments: the memo, then the value ' +

'and index (or key) of the iteration, and finally a reference to the entire list.';

var string_array = words.split(/[\s]/);

var mapped = _.map(string_array,
function(element, index) {

    var stat = {};
    if (element) {
        for (var i = 0; i < element.length; i++) {
            var c = element.charAt(i);
            if (c.match(/\w/)) {
                if (stat[c]) {
                    stat[c] += 1;
                } else {
                    stat[c] = 1;
                }
            }
        }
    }
    return stat;
});

var reduced = _.reduce(mapped,
function(memo, elem) {
    _.each(elem,
    function(val, key) {
        if (memo[key]) {
            memo[key] += val;
        } else {
            memo[key] = val;
        }
    });
    return memo;
},
{});
//方法二
var mapped = _.map(string_array,
function(element, index) {

    if (element) {
        return _.countBy(element.split(''),
        function(val) {
            return val;
        });

    }

});



發佈了27 篇原創文章 · 獲贊 2 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章