Quick javascript array question
Options
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎08-30-2023 05:46 AM
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
Options
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎08-30-2023 05:57 AM
why not use arrayUtil unique method after just getting dates from the value?
Regards,
Ankur
✨ Certified Technical Architect || ✨ 9x ServiceNow MVP || ✨ ServiceNow Community Leader
Ankur
✨ Certified Technical Architect || ✨ 9x ServiceNow MVP || ✨ ServiceNow Community Leader
Options
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎08-30-2023 05:58 AM
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);