关闭

UnderScore.js统计字符出现频率

198人阅读 评论(0) 收藏 举报
分类:
//方法一
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;
        });

    }

});



0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:17815次
    • 积分:431
    • 等级:
    • 排名:千里之外
    • 原创:26篇
    • 转载:4篇
    • 译文:0篇
    • 评论:0条
    文章分类