0

我有日期列表,我需要在其中检查重复日期和重复日期的出现次数,我需要在 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

4

2 回答 2

1

使用Underscore.js

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

例子:

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}

​</p>

于 2012-07-06T12:13:29.267 回答
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"]);
于 2012-07-02T13:16:56.997 回答