3

I am trying to find a string in a javascript array in the transformer of a mirth channel. Mirth throws an error when I try to use indexOf function. My understanding is that indexOf is something that browsers add in, rather than a native part of the javascript language itself. ( How do I check if an array includes an object in JavaScript? )

So is array.indexOf just not supported in Mirth? Is there any way to use .indexOf in Mirth? Maybe an alternate syntax? Or do I need to just loop thru the array to search?

Community
  • 1
  • 1
bernie2436
  • 22,841
  • 49
  • 151
  • 244

4 Answers4

2

This is how I search arrays in a Mirth js transformer:

var Yak = [];
Yak.push('test');

if(Yak.indexOf('test') != -1)
{
    // do something
}

Does this give you error?

nathan_jr
  • 9,092
  • 3
  • 40
  • 55
  • This method gives me an error. We're using Java 6, build 23, with Mirth 1.8.2. If you're using something newer, please let me know. – csj Oct 12 '12 at 06:53
  • I am using Mirth latest (2.2.1). – nathan_jr Oct 12 '12 at 23:45
  • 1
    turns out it was JVMs prior to 6.23 where this was broken. After playing around some more, and comparing Java versions, I can say that we have indexOf working on 6.23 or higher. I think it was down somewhere around 6.04 where it was still broken. – csj Dec 08 '12 at 00:16
1

Mirth uses the Rhino engine for Javascript, and on some earlier versions of the JVM, indexOf appeared to not be supported on arrays. Since upgrading our JVM to 1.6.23 (or higher), indexOf has started working. However, we still have legacy code that, when searching arrays of strings, I just use a loop each time:

var compareString = "blah";
var index = -1;
for (var i = 0; i < myArray.length; ++i)
{
    if (myArray[i] == compareString)
    {
        index = i;
        break;
    }
}

If you need to do this frequently, you should be able to use a code template to manually add the indexOf function to Array.

Set the code template to global access, and try out something like this (untested code):

Array.prototype.indexOf = function(var compareObject)
{
    for (var i = 0; i < myArray.length; ++i)
    {
        // I don't think this is actually the right way to compare
        if (myArray[i] == compareObject)
        {
            return i;
        }
    }

    return -1;
}
csj
  • 21,818
  • 2
  • 20
  • 26
1
var arr = ['john',1,'Peter'];

if(arr.indexOf('john') > -1)
{
    //match. what to do?
    console.log("found");
}
else
{
    console.log("not found");//not found .. do something 
}

Ali Yousuf
  • 692
  • 8
  • 23
MelB
  • 11
  • 5
-1
var i = ['a', 'b', 'c']

if(i.indexOf('a') > -1)
{
       ///do this, if it finds something in the array that matches what inside the indexOf()
}
else
{
    //do something else if it theres no match in array
}
KBriz
  • 333
  • 2
  • 7
  • 21