Junias Junias - 10 months ago 66
Javascript Question

Javascript: Filter Array with duplicate Dates

I´m using Angular2 and I have an array with Date-Objects (~1000).
Most of the Date-Objects have got the exactly same dates (for example 2016_11_02; Dates have no hours & minutes).
Normally there should be about ~10-20 different Dates in the Array.

Now i want to filter this array and delete the duplicate Dates.
So in the end there should be about ~10-20 Date-Objects in the array.

Here´s the code i tried:

let uniqueArray = duplicatesArray.filter(function(elem, pos) {
return channelEPGDates.indexOf(elem) == pos;
console.log('unique: ' + uniqueArray.length);

I know this is not correct, cause the unique-Array has the same length as the old array. But how can i compare the Dates itself in the filter-function?

Thanks so much!

Answer Source

I would map the dates to epoch time using the getTime method, and then map them back to Date objects.

let uniqueArray = duplicatesArray
.map(function (date) { return date.getTime() })
.filter(function (date, i, array) {
    return array.indexOf(date) === i;
.map(function (time) { return new Date(time); });