nickh
nickh

Reputation: 4841

Why does the result contain multiple copies of the same value?

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

Answers (2)

Kyle R
Kyle R

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

u.k
u.k

Reputation: 3091

Your verfication is wrong.

It should be if (values.indexOf(doc.value.toDateString()) != -1) return;

Upvotes: 3

Related Questions