我有两个看起来像的数组

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

最佳答案

这样做:

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

10-06 10:38