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

James Chun
Kilo Patron

@Tarasingh26 

 

The script runs fine if you 'hardcode' the values;

e.g. 

var catStr = "direct";
var categoryArr = "Legal,Direct,Indirect".split(',');

gs.info(categoryArr.indexOf(catStr));

 

Can you share the log when you run the following script?

var categoryArr = [];
var subcatArr = [];
var catStr = source.u_category; // Value is Direct in my example
gs.info('catStr ' + catStr + " type is " + typeof catStr);

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('categoryArr ' + categoryArr + " type is " + typeof categoryArr);
}

 

Cheers

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.

 

Thanks Maroon. It was space issue. It is working fine now.