计算列表中的重复日期以及计数中重复日期的出现次数

时间:2012-07-02 11:50:38

标签: javascript

我有一个日期列表,我需要检查重复项和重复日期的发生计数我需要在javascript中实现... 试着帮助我 预先感谢。 EX: { 12/11/2011, 12/11/2011, 11/4/2012, 12/6/2012, 12/6/2012, 12/6/2012} Desire output: {12/11/2011, 11/4/2012, 12/6/2012} count: 12/11/2011 =2 count: 12/6/2012 =3

2 个答案:

答案 0 :(得分:1)

使用Underscore.js

  

_。reduce(list,iterator,memo,[context])别名:inject,foldl也称为inject和foldl,reduce将值列表归结为a   单一价值。备忘录是减少的初始状态,每个   它的后续步骤应由迭代器返回。

Example:

var dates = [ '1/1/2006', '1/1/2006', '1/1/2007', '1/1/2007', '1/1/2007', '1/1/2006', '1/1/2012', '1/1/2006', '1/1/2009', '1/1/2012'];

var x = _.reduce(dates, 
            function(counts, date) {
                counts[date] = (counts[date] || 0) + 1;
                return counts;
            }, {});

alert(JSON.stringify(x)); 

可生产

{"1/1/2006":4,"1/1/2007":3,"1/1/2012":2,"1/1/2009":1}

答案 1 :(得分:0)

如果您的日期是字符串(存储为字符串),您可以尝试这样的事情:

var dates = ["12/11/2011", "12/11/2011", "11/4/2012", "12/6/2012", "12/6/2012", "12/6/2012"];
var dates_set = {}; // key will be date, and values will be count

for (var i = dates.length - 1; i >= 0; i--) { 
    var d = dates[i];
    if (dates_set.hasOwnProperty(d)) {  // already is in our set, just increase counter
        dates_set[d] = dates_set[d] + 1;;
    } else { // there is no such date, lets add it
        dates_set[d] = 1
    }

};
document.write(dates_set["12/11/2011"]);
document.write("<br />");
document.write(dates_set["12/6/2012"]);