Conversion of comma separated values into an array
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎02-21-2023 04:36 AM
Hello everyone,
How to convert comma separated values into an array?
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎02-21-2023 06:47 AM
Hi @hardikbendre ,
Please use the below to convert comma separated value into an array:
// dec stores the comma separated values
var dec = "service,now,community"
var colSplit = dec.split(",");
var arr=[];
for(i=0;i<colSplit.length;i++)
{
arr.push(colSplit[i]);
}
gs.print(JSON.stringify(arr));
Please mark this answer correct/helpful, if it resolve your issue.
Thanks !
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎02-21-2023 06:54 AM
var strValues = "1,2,3,4,5,6,7,8,9,10";
var arrValues = strValues.split(',');
gs.info("strValues = " + strValues + ", arrValues = " + arrValues);
for (i=0; i < arrValues.length; i++) {
gs.info("Array element: " + i + ", value: " + arrValues[i] + ".");
}
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎02-21-2023 07:23 AM
One would 1st call the string's split method:
var list = ' item 1, item 2 , ,item 3 ';
var array = list
.split(',');
gs.debug('\n[' + array.join(']\n[') + ']');
This prints:
*** Script: [DEBUG]
[ item 1]
[ item 2 ]
[ ]
[item 3 ]
Pretty all over the place.
For better result - where the leading and trailing spaces are removed - one would use trim before splitting:
var list = ' item 1, item 2 , ,item 3 ';
var array = list
.trim()
.split(',');
gs.debug('\n[' + array.join(']\n[') + ']');
This prints:
*** Script: [DEBUG]
[item 1]
[ item 2 ]
[ ]
[item 3]
Really only slightly better - only the 1st and the last items look good - and half of both only by chance (the one who entered the list did not add extra spaces after the last item and before the 1st one).
To take care of all extra spaces for all items that could exist due to sloppy fellow programmers composing the list or faulty data entry, one would switch the splitter to RegExp:
var list = ' item 1, item 2 , ,item 3 ';
var array = list
.trim()
.split(/\s*,\s*/g);
gs.debug('\n[' + array.join(']\n[') + ']');
This prints:
*** Script: [DEBUG]
[item 1]
[item 2]
[]
[item 3]
A lot better, almost there, just one problem remains: the 3rd item which is empty.
To take care of that problem one might filter the resulting array:
var list = ' item 1, item 2 , ,item 3 ';
var array = list
.trim()
.split(/\s*,\s*/g)
.filter(retainNotEmpty);
function retainNotEmpty (item) {
return '' != item;
}
gs.debug('\n[' + array.join(']\n[') + ']');​
This prints:
*** Script: [DEBUG]
[item 1]
[item 2]
[item 3]
Just about what one desires.
Filtering will also fix the issue of empty string ending up (not in a 0 length array, but) in an array with one item when split.