Reputation: 4841
With the following JavaScript, why does the output contain multiple copies of the same value?
reduce = function(docs) {
var values = [];
docs.forEach(function(doc) {
if (values.indexOf(doc.value) != -1) return;
values.push(doc.value.toDateString());
});
return values;
}
doc = {value: new Date("2012-01-01T00:00:00Z")}
reduce( [ doc, doc ] )
// => ["Sat Dec 31 2011", "Sat Dec 31 2011"]
Upvotes: 0
Views: 38
Reputation: 568
reduce = function(docs) {
var values = [];
if (values.indexOf(doc.value.toDateString()) != -1) return;
values.push(doc.value.toDateString());
return values;
}
doc = {value: new Date("2012-01-01T00:00:00Z")}
reduce(doc)
//["Sun Jan 01 2012"]
Try this. Why are you doing a foreach function if you only want one passed through? You should also only be passing doc
through once to the reduce function.
Upvotes: 0
Reputation: 3091
Your verfication is wrong.
It should be if (values.indexOf(doc.value.toDateString()) != -1) return;
Upvotes: 3