Filter function not working for Date (javascript)

I've tried to filter an array by a set date

var di = new Date(this.state.date.slice(0, 4),
                  this.state.date.slice(5, 7),
                  this.state.date.slice(8, 10),
                  '10',
                  '00');
var result2 = result.filter(function(number) {
  return (number[2] == di)
});

But the result is an empty array (result2).

Below is a screenshot of console.log(di) and one element of the array -

enter image description here

Upvotes: 3

Views: 1332

Answers (2)

Sebastian Krysiak
Sebastian Krysiak

Reputation: 911

You cannot compare two different objects in javascript using == This will return true only comparing the same instance of an object.

To make Your code work you can try converting the dates to strings.

var result2 = result.filter(function(number) {
  return (number[2].toString() == di.toString())
});

or by using the .getTime() method of Date object

var result2 = result.filter(function(number) {
  return (number[2].getTime() == di.getTime())
});

Upvotes: 6

kjh
kjh

Reputation: 15

The first argument to the filter function is an array element, not the array itself, so it should be:

result.filter( function(el) { return (el == di); } );

Upvotes: -3

Related Questions