1
years = [ Date, Date, Date  ]

// This gets date ascending order but not sure how can i remove duplicate   
this.years.sort(function(a, b) {
  let dateA:any = new Date(a); 
  let dateB:any = new Date(b);
  return (dateA - dateB);
});
console.log( this.years );

How can remove duplicate date in this sort function, Or do I need to write separately? and Is this script standard?

2
  • There's no way sort can change the length of an array. You should use filter. You can check this question Commented Jun 26, 2019 at 14:20
  • 1
    I just add a hint, the proposed solution in the linked answers may not work as-is, since they could just compare the references. For this reason, I advise you tu map with .map(date => date.getTime()) or if you want to be that cool guy, you can use date => +date Commented Jun 26, 2019 at 14:24

2 Answers 2

1

It's not possible to remove items while sorting as the sort function just move indexes. I would suggest you to get the unique elements first so the resulting array to sort is smaller and you don't sort elements that will be deleted.

Please, take a look at this answer to get the unique values:

const dates = [Date, Date, Date];
const uniqueDates = dates.filter((date, i, self) => 
  self.findIndex(d => d.getTime() === date.getTime()) === i
)

And after that:

const uniqueDatesSorted = uniqueDates.sort((a, b) => a -b)

Hope it helps!

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

2 Comments

When I trying this, it didn't worked for Date values. It works for other types, but I couldn't get it to work with Date. If you can provide a working example it can be helpful.
You're right! I've updated the answer. Let me know if it works!
0

Ok, sort can't remove duplicates, so in my solution I removed the duplicates first with map and filter and then applied the sort.

let myArray = [new Date(2019, 06, 28), new Date(2019, 07, 28), new Date(2019, 06, 28), new Date(2019, 07, 14), new Date(2019, 07, 01), new Date(2019, 07, 16), new Date(2019, 07, 14)]

let unique = myArray.map((date) => +date)
  .filter((date, i, array) => array.indexOf(date) === i)
  .map((time) => new Date(time));

unique.sort((a, b) => a - b);

console.log(unique)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.