js计算数组中每个元素出现的次数

计算数组中每个元素出现的次数

var names = [‘Alice’, ‘Bob’, ‘Tiff’, ‘Bruce’, ‘Alice’];

var countedNames = names.reduce(function (allNames, name) { if (name in allNames) { allNames[name]++; } else { allNames[name] = 1; } return allNames; }, {});

// countedNames is: // { ‘Alice’: 2, ‘Bob’: 1, ‘Tiff’: 1, ‘Bruce’: 1 }

 // 统计加点中,每个数字出现的次数
 function totallNum(arr) {
     var map = arr.reduce((m, x) => m.set(x, (m.get(x) || 0) + 1), new Map());
     return map;
 }; 

function countTimes(data) {
    var obj = {};
    return data.reduce(function(time, name) {
        if (name in time) {
            time[name]++;
        } else {
            time[name] = 1;
        }
        return time;
    }, {});
};

 countTimes([1,1,1,2,3,3,2])

 

    原文作者:dxj124
    原文地址: https://blog.csdn.net/dxj124/article/details/92804186
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞