Locate an element in an array array

Hello everyone, I have an array of elements. Each element is an array of elements.
image

[{"id":"4fc7389b1ee3ce61","type":"function","z":"22872ad18901ecfc","name":"find element","func":"\n// recupere le msg.payload : array : offsetBox label valeur unite description type nbByte  facteur \n/*\n[\n    [32, \"uint16\", 2, null, 100, \"ph:consigne\", null, \"phConsigne\"],    //iD = 20\n    [...]\n]\n*/\n\n//const trameMontanteParametresProtocole = flow.get(\"trameMontanteParametresProtocole\")\n//afficher le contenu du array qui contient \"phConsigne\"\n// il est Ă  id: 20\n\nlet localised = msg.payload.indexOf(\"phConsigne\")\nmsg.localised = localised\nreturn msg\n\n\n\n","outputs":1,"noerr":0,"initialize":"","finalize":"","libs":[],"x":800,"y":880,"wires":[["84a56d6cf338bc16"]]},{"id":"84a56d6cf338bc16","type":"debug","z":"22872ad18901ecfc","name":"localised","active":true,"tosidebar":true,"console":false,"tostatus":true,"complete":"true","targetType":"full","statusVal":"payload","statusType":"auto","x":1020,"y":880,"wires":[]},{"id":"4bd0b39beafd3d8f","type":"inject","z":"22872ad18901ecfc","name":"array","props":[{"p":"label","v":"phConsigne","vt":"str"},{"p":"payload"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"[[11,\"aa\"],[22,\"zz\"],[33,\"ee\"],[7.2,\"uint16\",2,null,100,\"phConsigne\"],[44,\"a\",\"rr\"],[55,\"tt\"],[66,\"yy\"],[77,\"uu\"]]","payloadType":"json","x":640,"y":880,"wires":[["4fc7389b1ee3ce61"]]}]

image

I would like to know the id of the element which contains a string for example "phConsigne" (in the example it should tell me 3).

I therefore use the method msg.payload.indexOf("phConsigne") but it does not find it and indicates "not found" -1

Do you know what the fault is?
Thanks

msg.payload.forEach((element,index) => {
    if (element.indexOf("phConsigne") > -1) msg.localised = index
});

return msg
1 Like
Object.keys(msg.payload).forEach(index => {
    
    let localised = msg.payload[index].indexOf(msg.label)
    if (localised != -1){
        msg.localised=index
    }

})

return msg


snap :rofl: :joy: :rofl:

OK yours is shorter :grinning: But to combine the two using the input of msg.label -

msg.payload.forEach((element, index) => {
    if (element.indexOf(msg.label) > -1) msg.localised = index
});
return msg

:star_struck: it's beautiful when you know! thanks guys @smcgann99 @KarolisL

For fun: In a 1 liner :wink: ...

msg.localised = msg.payload.map((e, i) => e.includes(msg.label)?i:null).find(e => e!==null)
return msg

2 Likes

wow then there! I never would have found!! :clap:

Now you're just showing off :thinking:

1 Like

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