Reputation: 87
I've been testing with the following code and it appears not to be functioning as expected:
var obr41 = msg['OBR']['OBR.4']['OBR.4.1'].toString();
var list = ["THIS","THAT","OTHER"];
for (var i = 0, len = list.length; i < len; ++i)
{
if (obr41 !== list[i])
{
msg['OBR']['OBR.4']['OBR.4.1'] = "NOMATCH";
break;
}
}
If I shorten the array to just one value, then it works. Otherwise, it will return "NOMATCH" when using any of the values in the array. Any help on this would be greatly appreciated!
Thank you - Matt
Upvotes: 0
Views: 45
Reputation: 459
You are iterating over three different elements and comparing them to a single member of a an object array. If a difference is found, you break the loop and a difference will always be found because the three members are different.
You probably wanted to break if a match is found and not if a match is not found
var obr41 = msg['OBR']['OBR.4']['OBR.4.1'].toString();
var list = ["THIS","THAT","OTHER"];
var found = false;
for (var i = 0, len = list.length; i < len; ++i)
{
if (obr41 === list[i])
{
found = true;
break;
}
}
if(!found) msg['OBR']['OBR.4']['OBR.4.1'] = "NOMATCH";
Upvotes: 1
Reputation: 2870
obr41
is a single value, and the list contains three different values. That means you'll always find an item in list
that does not match obr41
.
I think what you want is to set a variable if there's a match, and if the variable is never set, there was no match.
var obr41 = msg['OBR']['OBR.4']['OBR.4.1'].toString();
var list = ["THIS","THAT","OTHER"];
var foundMatch = false;
for (var i = 0, len = list.length; i < len; ++i)
{
if (obr41 !== list[i])
{
foundMatch = true;
break;
}
}
if (!foundMatch) {
msg['OBR']['OBR.4']['OBR.4.1'] = "NOMATCH";
}
Or you could use .inludes()
instead, which is cleaner.
var obr41 = msg['OBR']['OBR.4']['OBR.4.1'].toString();
var list = ["THIS","THAT","OTHER"];
if (!list.includes(obr41)) {
msg['OBR']['OBR.4']['OBR.4.1'] = "NOMATCH";
}
Upvotes: 1