从 Javascript 中的另一个数组创建出现次数数组

Create an array of number of occurrences from another array in Javascript

我有两个数组,看起来像

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

您可以 map 覆盖 monthRange 然后过滤 monthNames 到 return 每个月的出现次数:

monthRange.map(function(month) {
    return monthNames.filter(function(n) { return n === month }).length;
});

这样就可以了:

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

使用下划线你可以这样做:

_.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)

尝试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...