Quick javascript array question

e_wilber
Tera Guru
I have an array that contains a string of dates and times. Sometimes we get the same date in there but with a different time.

I need to remove all duplicate dates from this array and I tried the following but it keeps adding 09/07 back into the new array twice rather than just once. How do I go through and clean up this array? I don't care about the time but we can't have duplicate dates.
 
The output is: 
*** Script: 08/31/2023 07:25:47,09/01/2023 07:25:47,09/05/2023 07:25:47,09/07/2023 07:25:47,09/07/2023 19:00:00
Which is bad because it has 9/7 in there twice.
 
var dates = ["08/31/2023 07:25:47","09/01/2023 07:25:47","09/05/2023 07:25:47","09/07/2023 07:25:47","09/07/2023 19:00:00]"];

var sanitizedDates = [];
for (var i=0; i<dates.length; i++) {
    var dateSplit = dates[i].split(' ');
    gs.print(dateSplit[0]);  

    if (sanitizedDates.indexOf(dateSplit[0]) === -1) {
        sanitizedDates.push(dates[i]);
    }
}

gs.print(sanitizedDates);
2 REPLIES 2

Ankur Bawiskar
Tera Patron
Tera Patron

@e_wilber 

why not use arrayUtil unique method after just getting dates from the value?

 

Regards,
Ankur
✨ Certified Technical Architect  ||  ✨ 9x ServiceNow MVP  ||  ✨ ServiceNow Community Leader

Gunjan Kiratkar
Kilo Patron
Kilo Patron

Hi @e_wilber ,

Try below script :

var dates = ["08/31/2023 07:25:47","09/01/2023 07:25:47", "09/01/2023 07:27:47","09/05/2023 07:25:47","09/07/2023 07:25:47","09/07/2023 19:00:00"];

var sanitizedDates = [];
var uniqueDates = [];

for (var i = 0; i < dates.length; i++) {
    var dateSplit = dates[i].split(' ');
    var datePart = dateSplit[0];

    if (uniqueDates.indexOf(datePart) === -1) {
        uniqueDates.push(datePart);
        sanitizedDates.push(dates[i]);
    }
}

gs.log(sanitizedDates);

Please Mark My Response as Correct/Helpful based on Impact
Regards,
Gunjan Kiratkar
2X ServiceNow MVP
Community Rising Star 2022
Youtube : ServiceNow Guy