我有两个看起来像
的数组var monthNames = [ "January", "January", "January", "April", "April", "December", "August", "August", "November", "November", "November", "December" ];
var monthRange = [ "January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December" ];
现在我想知道我应该如何在JS中工作,这样我就可以获得一个新的数组,其中包含12个元素(每月一个)并计算它。所以它会是这样的 -
[3, 0, 0, 2, 0, 0, 0, 2, 0, 0, 3, 1]
此处的计数是monthRange
的顺序,它为monthNames
中的每个月提供了计数。
所以这里
January : 3,
April: 2,
December: 1,
August: 2,
November: 3,
December : 1
答案 0 :(得分:2)
这样就可以了:
var counts = monthRange.map(function(val) {
var count = 0;
for (var i = 0, j = monthNames.length; i < j; i++) {
if (val === monthNames[i]) count++;
}
return count;
});
答案 1 :(得分:1)
您可map
超过monthRange
,然后过滤monthNames
以返回每月的出现次数:
monthRange.map(function(month) {
return monthNames.filter(function(n) { return n === month }).length;
});
答案 2 :(得分:1)
使用下划线你可以这样做:
_.reduce(array, function(memo, month) {
memo[month] = (memo[month] === undefined ? 0 : memo[month]) + 1;
return memo
}, {})
在您的情况下,它看起来像
var countMonths = function(array, m) {
return _.reduce(array, function(memo, month) {
memo[month] = (memo[month] === undefined ? 0 : memo[month]) + 1;
return memo
}, m)
}
var memo = countMonths(monthNames, {})
memo = countMonths(monthRange, memo)
答案 3 :(得分:1)
尝试Object
跟踪频率:
var freq = function(list) {
var o = {};
var l = list.length;
var v;
while (v = list[--l])
o[v] = o[v] !== undefined ? o[v] + 1 : 1;
return o;
};
console.log(freq(["January", "January", "January", "April", "April", "December", "August", "August", "November", "November", "November", "December"]));
alert(JSON.stringify(freq(["apple", "mangoe", "apple"])));
Open console...