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

Swapna Abburi
Mega Sage
Mega Sage

Hi @xiyan_li 

 

try below code snippet.

var str2 = new ArrayUtil().unique(str1);

Hello,The following error has occurred:

xiyan_li_0-1726636259440.png

 

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.  

Mani A
Tera Guru

1st approach:

 

var str2 = []; 
var str1=['a','b','a','c'];
for (var i = 0; i < str1.length; i++) {
  if (str2.indexOf(str1[i]) === -1) {
    str2.push(str1[i]);
  }
}

 

@xiyan_li 

 

For removing duplicate values in array, Use the built-in ArrayUtil Script Include:

2nd approach : var noDuplicates = new ArrayUtil().unique(str1);