zafirzarya
zafirzarya

Reputation: 153

Map with dates as key doesn't retrieve items correctly

I am trying to build a map which will be something of the type: key: date -> values: list of objects

For that purpose I've got the following piece of code:

componentDidMount(){
    let allPredictions = listAllPredictions();
    this.predictions = new Map();

    for (let i = 0; i<allPredictions.length; i++) {
        let prediction = allPredictions[i];

        if (!this.predictions.has(prediction.tsPredictionFor)){
            this.predictions.set(prediction.tsPredictionFor, []);
        }

        let predictionsForDate = this.predictions.get(prediction.tsPredictionFor);
        predictionsForDate.push(prediction);
    }
    let d = new Date(2019, 1, 10, 0, 0, 0, 0);

    console.log('Prediction for date ' + d + ': ' + this.predictions.get(d));
    console.log('All predictions: ')
    console.log(this.predictions)

    //this.setState({activePredictions: listActivePredictions()})
}

What doesn't seem to work is that the map cannot compare 2 dates correctly. I noticed that the .has function returns false all the time, even though there are entries with same date.

These are the logs: logs

As you can see, the following indices have the same date: 0 and 3, 1 and 4, 2 and 5, but for some reason the map cannot detect this, so for every entry it creates a new list (as you can see: Array(1)).

What is the reason behind this?

Upvotes: 2

Views: 45

Answers (1)

Treycos
Treycos

Reputation: 7492

The Date object does not override the === operator, meaning that what is going to be compared is whether or not they have the same reference.

As a simple example, take the following code :

console.log(new Date() === new Date())

This is always going to return false no matter what because both created objects have a different reference.

However, you can use the string generated by formatting them as a key :

console.log((new Date()).getTime() === (new Date()).getTime())

Upvotes: 2

Related Questions