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.

Remove string from comma seperated field

sainath3
Giga Guru

Hi All,

Requirement: Remove the incident number from the field (comma separated).

 

Remove INC0008112 from the below field(Incidents).

sainath3_0-1693306394154.png

 

 

my code:

var arr = ['INC0008001', 'INC0008112'];
var len = arr.length;
for (i = 0; i < len; i++) {
var dft = new GlideRecord('u_defect');
dft.addEncodedQuery('u_incidentsLIKE' + arr[i]);
dft.query();
while (dft.next()) {
var inc = dft.u_incidents;
var result = inc.replace(arr[i], '');
dft.u_incidents = result;
dft.update();
}
}

Output:

INC0006733,,INC0008987//Here comma(,) is showing.

expected Output:

INC0006733,INC0008987.

 

Can you please help me.

 

 

4 REPLIES 4

Anurag Tripathi
Mega Patron
Mega Patron

Hi,

 

 

You are facing this issue because you re not remove that incident form the array but replacing it with a blank. You need to skip it altogether.

Here is an example

// the starting array
const arrayOfLetters = ['a', 'b', 'c', 'd', 'e', 'f'];

// here the array is copied, without the first element
const copyWithoutFirstElement = arrayOfLetters.slice(1);

// arrayOfLetters is unchanged
console.log(arrayOfLetters) // ['a', 'b', 'c', 'd', 'e', 'f']

// and copyWithoutFirstElement contains the letters from b to f
console.log(copyWithoutFirstElement) // ['b', 'c', 'd', 'e', 'f']

 

 

 

-Anurag

Hi Anurag,

Thanks for the reply.

 

I want Dynamic functionality, whatever the incidents are there in an array those should remove.

This is dynamic only, try this

var Orig= ['a', 'b', 'c', 'd', 'e', 'f'];
var x = 'e' ; //item to be removed, pass any item here
var findloc = Orig.indexOf(x);
Orig.splice(findloc, 1 ); //removing item from array
alert(Orig);
-Anurag

Peter Bodelier
Giga Sage

Hi @sainath3,

 

This script should work for you:

var toRemove = ['INC0008001', 'INC0008112'];
var encodedQuery = 'u_incidentsLIKE';
var len = toRemove.length;
for (i = 0; i < len; i++) {
	if (i != 0){
	encodedQuery += '^ORu_incdentsLIKE';
	}
	encodedQuery += toRemove[i];
}
	var dft = new GlideRecord('u_defect');
	dft.addEncodedQuery(encodedQuery);
	dft.query();
	while (dft.next()) {
		
		var orig = dft.getValue('u_incidents').split(',');
		for( var i =orig.length - 1; i>=0; i--){
			for( var j=0; j<toRemove.length; j++){
				if(orig[i] === toRemove[j]){
					orig.splice(i, 1);
				}
			}
		}
		dft.u_incidents = JSON.stringify(orig);
		dft.update();
}

Help others to find a correct solution by marking the appropriate response as accepted solution and helpful.