Reputation: 5643
I m Trying to remove the duplicate date from an array of Date like
let dates = ["date1","date2","date1","date3"];
I convert dates into Set but it's doesn't remove duplicate, but when I try it with other datatypes instead of Date in work, Where is the problem?
let uniq = dates => [...new Set(dates)
];
Upvotes: 1
Views: 2310
Reputation: 68635
Because your dates are objects they will we compared via references. Two objects can't be equal though they have all equal properties.
const a = { name: 'Test' }
and const b = { name = 'Test' }
have identical values but their references (address in the memory) are not equal. So why Set does not work in your case.
You can work with their string representations. Strings are going to be compared via their value. const a = 'Test'
and const b = 'Test'
are identical in this case. Map them using toString
function and then insert them into the Set. Same dates will have the same string representations and so they will not be unique.
const dates = [
new Date(), // Will be the same as the below 3 dates at runtime
new Date(),
new Date(),
new Date(),
new Date(2015, 1, 1)
];
const uniqueDates = [...new Set(dates.map(date => date.toString()))];
console.log(uniqueDates);
Upvotes: 3