Multiple comma-separated strings to remove duplicates

xiyan_li
Tera Contributor
Hello, I want to remove duplicates from multiple comma-separated strings, what can I do? Such as: str1 = 'abc,str_abc,try,abc,str_abc"; After deleting duplicates: str2 = 'abc,str_abc,try"; Who can tell me how to facilitate judgment?
1 ACCEPTED SOLUTION

Chetan Mahajan
Kilo Sage
Kilo Sage

Hello @xiyan_li ,

                          Please try below script i have tried in background script and its working

var str1 = 'abc,str_abc,try,abc,str_abc';
var uniqueValues = [];
var check = {};
if (str1) {
    var items = str1.split(','); // split in array

    for (var i = 0; i < items.length; i++) {
        var item = items[i].trim(); // Trim whitespace
        if (!check[item]) {
            check[item] = true; // Mark this item as check
            uniqueValues.push(item); // Add it to the unique values
        }
    }
}
// Join the unique values back into a string
var str2 = uniqueValues.join(',');
gs.print('Original string: ' + str1);
gs.print('String without duplicates: ' + str2);

O/P 

*** Script: Original string: abc,str_abc,try,abc,str_abc
*** Script: String without duplicates: abc,str_abc,try

Kindly mark correct and helpful, if applicable.  

View solution in original post

7 REPLIES 7

xiyan_li
Tera Contributor

Hi, I tried using indexOf, but it didn't solve my problem.

I'm running it in an onChange script where I need to remove duplicate values in multiple strings separated by commas,So I tried to use indexOf to solve it, but it didn't solve my problem.

 

I also used ArrayUtil, but there was an error during operation

Community Alums
Not applicable

Hello @xiyan_li 

Please try the following code:

var str1 = 'abc,str_abc,try,abc,str_abc';
var splitValue = str1.split(',');
var str2 = new ArrayUtil().unique(splitValue);

Mark the solution as accepted and helpful.

Thanks




Pranesh072
Mega Sage
Mega Sage

 

 

var str1 = 'abc,str_abc,try,abc,str_abc';

var a1 = str1.split(',');

  var a = [];
        for (var i = a1.length - 1; i >= 0; i--) {
            if (a.indexOf(a1[i]) === -1)
                a.push(a1[i]);
        }
alert(a.toString()); //str_abc,abc,try