Why index returns -1 in both cases if element in an array found or nott

Tarasingh26
Tera Expert

Hi All,

 

I am trying to implement transform map script in which I need to check if an element is present in array or not. But I am wondering to see in both scenarios if element found or not , index value is always returned -1. Please help me if anyone faced same kind of issue. Attached is screenshot of script.

 

 

Thanks,

Tara Singh 

1000156440.jpg

4 REPLIES 4

Yousaf
Giga Sage

Hi Tarasingh,


Please try to make use of arrayutil class.
ArrayUtil - Global 

 

Please mark correct and Helpful if it helps.


***Mark Correct or Helpful if it helps.***

kkrushkov
Mega Sage

Hi, @Tarasingh26 

 

Try:

categoryArr.indexOf(catStr) > -1


I hope this information is useful to you! If you have any further questions or need clarification on any point, feel free to ask.

 

Best regards,
kkrushkov

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

@Tarasingh26 

 

Why are you using an 'if' statement? This way, you're not iterating through all the records. This way you are checking if the first value in the array is the value you are searching for.


So, for example, if you have an array - [hardware, software, network, database], your approach will return false when searching for the value 'network', regardless of its presence in the array. This is because in the 'if' statement, you are iterating only once and taking the first value in the array.

Hope this clarifies the situation.

 

Consider using a 'while' loop instead. Also, when adding elements to an array, you should use push().

 

Additionally, you are pushing the display value of the u_category field into the array, but later you are searching for the string value of the field using getValue()- categoryArr.indexOf(catStr). Consider refactoring this approach for consistency.

 

Try the following: 

 

 

while(gr.next()){
    categoryArr.push(gr.getDisplayValue('u_category').split(', '))
}