计算数组中每个元素出现的次数
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])