Why indexOf is returning always -1 even if element is present in array

Tarasingh26
Tera Expert

1000156084.jpg

Hi All,

 

I am implementing scenario of transform map script in which I need to check if category array contains element of source category and perform few tasks . But in attachment at 12 number line index is always return -1 even if element is present in categoryArr. Could someone please help this why it is returning always -1?

Thanks,

Tara Singh 

1000156084.jpg

1 ACCEPTED SOLUTION

maroon_byte
Mega Sage

 

As you mentioned your array is: Legal, Direct, Indirect

Hence your input value is "Direct" but your array contains " Direct"... leading space 🙂

 

But why convert to array? Try below:

var catStr = "Direct";
var categoryArr = "Legal, Direct, Indirect";
gs.info(categoryArr.toLowerCase().indexOf(catStr.toLowerCase()));
 
Note: Always compare strings with lower or upper case.

 

View solution in original post

12 REPLIES 12

@Amit Pandey  here is script.

 

Here is the script in text format.

 

var categoryArr=[];
var subcatArr=[];
var catStr=source.u_category; // Value is Direct in my example
var gr = new GlideRecord("sn_risk_advanced_lee_category_combination_lookup");
gr.addQuery('u_impact_type', source.u_impact_type);
gr.query();
if(gr.next())
{
categoryArr=gr.getDisplayValue('u_category').split(','); // Array values are Legal, Direct, Indirect
gs.info("Index is" +categoryArr.indexOf(catStr);// Here it prints Index is -1 but it should not print -1 because catStr=Direct is present in Legal, Direct, Indirect array.
if(categoryArr.indexOf(catStr) > -1) // Here is issue it is always returns =-1 even catStr=Direct is present in Legal, Direct, Indirect array.
{
subcatArr=gr.getDisplayValue('u_sub_category').split(',');

}

SANDEEP28
Mega Sage

@Tarasingh26  Remove toString() method which you have used to convert "source.u_category" to string format. It will work

 

 If I could help you with your Query then, please hit the Thumb Icon and mark as Correct !!

@SANDEEP28 Thanks for reply. I tried it but it is not working.

Anubhav24
Mega Sage
Mega Sage

Hi @Tarasingh26 ,

In this line 
if(categoryArr.indexOf(source.u_category).toString() > -1) can you try and changing it to 
if(categoryArr.indexOf(source.u_category) > -1) and see if it works or not.

Please mark helpful/correct if my response helped you.

Tarasingh26
Tera Expert

@Anubhav24 Thanks for reply but it is not working.