我有一个日期列表,我需要检查重复项和重复日期的发生计数我需要在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
答案 0 :(得分:1)
_。reduce(list,iterator,memo,[context])别名:inject,foldl也称为inject和foldl,reduce将值列表归结为a 单一价值。备忘录是减少的初始状态,每个 它的后续步骤应由迭代器返回。
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"]);