I have a method that checks a con
variable as true
or false
and return a device tag for each device, I could only get the first tag even though the 2nd, 3rd condition is true. How to check all the conditions and return all the devices.
function populateDevices(){ if(ethsrc[0].con === true) { return ethsrc .filter(i => i.srcid === 0) .map((i,idx) => ( <Device name={i.name} srcid={i.srcid} inst={idx} drt={i.drt} data={i.data} /> )) } if(ebmcard[0].con === true){ return ebmcard .filter(i => i.srcid === 0) .map((i,idx) => ( <Device name={i.name} srcid={i.srcid} inst={idx} drt={i.drt} data={i.data} /> )) } if(mi5module[0].con === true){ return mi5module .filter(i => i.srcid === 0) .map((i,idx) => ( <Device name={i.name} srcid={i.srcid} inst={idx} drt={i.drt} data={i.data} /> )) } }
Advertisement
Answer
As soon as you make a return
, the function stops, everything after won’t get executed. You could use a result
array, concatenate with each array for each condition, like so:
function populateDevices(){ let result = [] if(ethsrc[0].con === true) { result = result.concat(ehsrc .filter(i => i.srcid === 0) .map((i,idx) => ( <Device name={i.name} srcid={i.srcid} inst={idx} drt={i.drt} data={i.data} /> ))) } if(ebmcard[0].con === true){ result = result.concat( ebmcard .filter(i => i.srcid === 0) .map((i,idx) => ( <Device name={i.name} srcid={i.srcid} inst={idx} drt={i.drt} data={i.data} /> ))) } if(mi5module[0].con === true){ result = result.concat(mi5module .filter(i => i.srcid === 0) .map((i,idx) => ( <Device name={i.name} srcid={i.srcid} inst={idx} drt={i.drt} data={i.data} /> ))) } return result; }