How to fetch array if it contains particular string?

Gayathri5
Tera Guru

Hi All,

 

I have array it contains

var allarr =[];

var incarr =[];

allarr=INCXXXX, INCXXXX, PRBXXXX, SCTXXXXX, PRBXXXX;

 

now i am checking if allarr contains INC separate it in another array which is not working

for(var x in allarr){

gs.log("Inside for loop:"+allarr);//going here

if(allarr[x].indexof('INC') > -1){

incarr.push(allarr[x]);

gs.log("Inside if:"+incarr); //not going inside if loop

}

}

 

after going inside if loop i want to separate all incidents in one array, can any one help me pls

 

Regards,

Gayathri

 

17 REPLIES 17

Rahul Talreja
Mega Sage
Mega Sage

Hi Gayathri,

You can make changes referring the below script.

var allarr =['INCXXXX', 'INCXXXX', 'PRBXXXX', 'SCTXXXXX', 'PRBXXXX'];
var incarr =[];
var temp,i;
for(i = 0; i < allarr.length; i++)
{
temp = allarr[i];
if(temp.slice(0, 3) == 'INC')
{
incarr.push(temp);
}
}
gs.log(incarr);

Please mark Correct/Helpful if applicable.
Thanks

Please mark my response correct/helpful as applicable!
Thanks and Regards,
Rahul

Hi Rahul,

 

Not working, it is not going inside the for loop

Nick Parsons
Mega Sage

When you loop over an array, you shouldn't use a for..in loop to access its indexes. A for..in loop is used to loop over an object's properties, so a for..in loop on an array could potentially loop over non-indexes, which can cause you problems (more here). Use .forEach() or a standard for loop to loop over an array instead.

With that said, it seems like you want to filter your array. You can do this with the Array.prototype.filter() method, and use ServiceNow's string .startsWith() method to keep all items that start with "INC".

See example below:

var allarr= ['INCXXXX', 'INCXXXX', 'PRBXXXX', 'SCTXXXXX', 'PRBXXXX'];
var allInc = allarr.filter(function(number) {
  return number.startsWith("INC");
});
// allInc = ['INCXXXX', 'INCXXXX']

Nick posted my reply before I did. The only difference is I had allarr as a String.

var allarr = 'INCXXXX, INCXXXX, PRBXXXX, SCTXXXXX, PRBXXXX';
allarr = allarr.replaceAll(' ', '').split(',');

var incarr = allarr .filter(function(n) {
    return n.startsWith('INC');
});
gs.info(incarr);

Nice, I wasn't aware ServiceNow has support for .replaceAll() considering that in JS its an ES12 method and we're stuck in ES5 :,). I guess we can also use .split(", ") if we didn't want to use replace.