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

    }

});



阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/fight4gold/article/details/46789785
个人分类: JS
上一篇Java系统多个JSSE认证
下一篇joda-time实现Timehelper
想对作者说点什么? 我来说一句

从txt文件中读取并统计字符频率

2009年04月07日 138KB 下载

没有更多推荐了,返回首页

关闭
关闭