Search code examples
arraysfilternode-red

node red filter array with array


I have this node red test setup where I want to filter an array of objects with an array. The problem is, the test setup returns an unfiltered copy of the original array. I have already posted another question about this where comments suggested I am doing everything right. The question got closed by a moderator. But my problem remains unsolved.

could anyone tell me where I go wrong?

the input array payload is an array of elements:

[{"altname":"melon"},{"altname":"cherry"},{"altname":"banana"}]

the filter array exclude has 2 elements:

[["melon"],["banana"]]

I expect the output array to have only 1 element:

[{"altname":"cherry"}]

my setup:

[{"id":"b4b2e91f.8e4368","type":"inject","z":"42edc0b9.7ba91","name":"","props":[{"p":"payload"},{"p":"exclude","v":"[[\"melon\"],[\"banana\"]]","vt":"json"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"[{\"altname\":\"melon\"},{\"altname\":\"cherry\"},{\"altname\":\"banana\"}]","payloadType":"json","x":1650,"y":320,"wires":[["3fbdbc18.951c94"]]},{"id":"3fbdbc18.951c94","type":"function","z":"42edc0b9.7ba91","name":"cycle counter","func":"\n\nmsg.payload = msg.payload.filter(el => !msg.exclude.includes(el.altname));\n\nnode.warn(msg.payload);\nreturn msg;","outputs":1,"noerr":0,"initialize":"","finalize":"","libs":[],"x":1810,"y":320,"wires":[["ab67374c.c64458"]]},{"id":"ab67374c.c64458","type":"debug","z":"42edc0b9.7ba91","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"true","targetType":"full","statusVal":"","statusType":"auto","x":2040,"y":300,"wires":[]}]

in addition to the comment bellow here is my setup as a description:

Inject node:

msg.payload = [{"altname":"melon"},{"altname":"cherry"},{"altname":"banana"}]
msg.exclude = [["melon"],["banana"]]

function node:

msg.payload = msg.payload.filter(el => !msg.exclude.includes(el.altname));
node.warn(msg.payload);
return msg;

Solution

  • The problem is that your exclude array is a 2D array not a simple single depth array.

    msg.exclude should be:

    ["melon","banana"]
    

    For the code you have to work correctly.