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?

ShibinRagh
  • 6,530
  • 4
  • 35
  • 57
  • There's no way `sort` can change the length of an array. You should use `filter`. You can check [this question](https://stackoverflow.com/questions/9229645/remove-duplicate-values-from-js-array) – Christian Vincenzo Traina Jun 26 '19 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` – Christian Vincenzo Traina Jun 26 '19 at 14:24

2 Answers2

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!

Alvaro
  • 1,853
  • 18
  • 24
  • 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. – Pietro Nadalini Jun 26 '19 at 14:52
  • 1
    You're right! I've updated the answer. Let me know if it works! – Alvaro Jun 26 '19 at 15:00
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)
Pietro Nadalini
  • 1,722
  • 3
  • 13
  • 32