Return Array of Unique Dates from Date Array


In our angularjs app we’re receiving an array of dates that then need to be filtered out to only return an array full of unique dates (not strings). I tried some of the answers on SO but I think because I’m comparing dates and not strings – I’m yielding different results. Any help on what the best approach is would be very helpful. enter image description here


You are right, date equality is different from string equality. Dates are objects, and the === comparator for objects compares them by reference, not value. Since {} === {} in JS is false, two Dates will never be equal to each other. So, let’s just turn the dates into numbers:

let dates = [new Date(), new Date('1/1/11'), new Date('1/1/11'), new Date('1/4/66')]

let uniqueDates = dates
                   .map(s => s.getTime())
                   .filter((s, i, a) => a.indexOf(s) == i)
                   .map(s => new Date(s));

The logic with indexOf is that every unique value should be present only at its own position; any others are duplicates (s is current item, i is current index, and a is the array itself). Then we map the array back into Dates and return it.

Answered By – joh04667

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published