Join the #BuildWithBuildAgent Challenge! Get recognized, earn exclusive swag, and inspire the ServiceNow Community with what you can build using Build Agent.  Join the Challenge.

splitting multiple lists, then joining into single array

davilu
Mega Sage

Hi Everyone, I have a question regarding comma separated lists and arrays.   Below is my simple server script that queries a Forms table and returns back all the forms listed for each row:

var docSet = new GlideRecordSecure('forms');

docSet.query();

while(docSet.next()){

        data.formType = docSet.getDisplayValue('form_type');

gs.addInfoMessage(data.formType);

}

The gs info message returns this, which is correct:

find_real_file.png

I want to split all of the comma separated items and return it all in the same array.

sampleArray = [ sf 61, sf306, sf2817, sf 2808, sf256, sf181 ]

I've tried samplelist.split(','), but can't seem to get it to work correctly.   Can someone help with this syntax?

1 ACCEPTED SOLUTION

Brian Dailey1
Kilo Sage

Hi David,



I don't know if this matters to your requirement, but I like to use an object as an intermediate to eliminate duplicates when building lists from multiple sources.




var docSet = new GlideRecordSecure('forms');  


docSet.query();



var uniqueForms = {};


while(docSet.next()){  


        var docSetForms = docSet.getDisplayValue('form_type').split(',');  


        //Using the value also as the key for uniqueForms{} will result in only one instance of any value.


        for(i=0;i<docSetForms.length;i++){


                uniqueForms[docSetForms[i]] = docSetForms[i];


        }


}



var listUniqueForms = [];



for(var m in uniqueForms){


      listUniqueForms.push(m);


}


var strList = listUniqueForms.join();



//Either return as an array (listUniqueForms)


//Or as a string (strList).





Thanks,


-Brian


View solution in original post

11 REPLIES 11

Hi David,



Could you paste the latest version of your code?   And also, what value are you getting from   formReview.getDisplayValue('form_type')?



Using indexOf() does work slightly differently on strings vs. arrays.   For a string, it will return the character position at which the match found starts... for an array it will return the index of the array value that matches.




Thanks,


-Brian


Short update to this method, I'm still a big fan of using an object to de-dupe lists and or combine lists.

 

At some later point in time, I also found that you can use Object.keys(..) in place of that second for() loop to grab the unique list.

 

(e.g.)

var listUniqueForms = Object.keys(uniqueForms);

 

 

 

-Brian