Егор Кротенко Егор Кротенко - 4 months ago 21
Javascript Question

filter fuction not working for Date (javascript)

try filter array by 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 get empty array result2

this is screen of console.log (di) and one element of array
enter image description here

Answer Source

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())
});