1

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)];

4
  • Your date1 and the others are simple dates like 2018-06-07 11:42 ? Commented Jun 7, 2018 at 7:42
  • 1
    If the dates are Objects, then they'll never === each other if they were created separately. If you want to deduplicate like that, you could convert the dates to timestamps first Commented Jun 7, 2018 at 7:43
  • stackoverflow.com/questions/11704971/… Commented Jun 7, 2018 at 7:45
  • @SurenSrapyan not date object contain date with 0 hour, minute, sec and milisecond Commented Jun 7, 2018 at 8:12

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

9 Comments

"The Set object lets you store unique values of any type, whether primitive values or object references." developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
With objects it will compare references
Cleverness is all well and good, but likely the OP has no idea why the above does what it does, nor why the Dates are now Strings.
@RobG Adding some explanation
Rather than parsing strings, consider using time values to avoid all parsing: [...new Set(dates.map(date => +date))].map(tv => new Date(tv)). Also worth noting that the resulting array will be new Dates, not references to the original Dates (which may be an issue).
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.