Creating a Lookup Table with double digits

Hi community!

I've been using a look up function that I've created for some time now and it's been working well,,,, until today that I ran into a scenario that has double digits.

When I inject the value 1 through 9 everything works perfectly. When I start doing double digits I get a double replacement, see picture of the output of a debug node when I inject the value 1, 9, 11, 15.

image

When I inject 11 the output replaces two times the number 1.

Any suggestions on how to read and replace "11" versus "1 and 1" ?

re-write the function in reverse order will work, but it may not be the best solution.

Can you show us what is inside msg.payload immediately before this function?

You can make use of regular expressions to look if there is no digit before and after the match:

You can find a better explanation why it works here: regex101

EDIT:
Maybe it even better to use /(?<!(\w))1(?!\w)/gi. As you also don't want to replace "L1" with anything, only numbers that aren't next to any word character: a-zA-Z0-9_.

If msg.payload coming into the function is a number, then you could just use a lookup array.
e.g

[{"id":"3fea8003.98bac8","type":"inject","z":"30af2d3e.d94ea2","name":"","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"3","payloadType":"num","x":180,"y":120,"wires":[["88e2c287.49512"]]},{"id":"88e2c287.49512","type":"function","z":"30af2d3e.d94ea2","name":"","func":"const lookup = [\n    null,\n    \"L1\",\n    \"L2\",\n    \"L1-L2\",\n    \"L3\",\n    \"etc\"\n];\nmsg.payload = lookup[msg.payload] + \" Connected\";\nreturn msg;","outputs":1,"noerr":0,"initialize":"","finalize":"","libs":[],"x":340,"y":140,"wires":[["4e45a50.133c95c"]]},{"id":"bfac3654.beb8f","type":"inject","z":"30af2d3e.d94ea2","name":"","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"4","payloadType":"num","x":175.3333282470703,"y":157.33334350585938,"wires":[["88e2c287.49512"]]},{"id":"4e45a50.133c95c","type":"debug","z":"30af2d3e.d94ea2","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","statusVal":"","statusType":"auto","x":560,"y":120,"wires":[]}]
const lookup = [
    null,
    "L1",
    "L2",
    "L1-L2",
    "L3",
    "etc"
];
msg.payload = lookup[msg.payload] + " Connected";
return msg;
1 Like

Thanks for this suggestion Steve, I did in fact try this out before reaching out to the community. It provided an unexpected result which caused me to seek advice from the pros.

A reply from Hopperpop did the trick :blush:

This did the trick !

Many thanks to your suggestion Hopperpop!!!

This community is awesome!

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.