Home > Mobile >  How to shorten multiple if statements (not if else)
How to shorten multiple if statements (not if else)

Time:06-16

I have an array in which i want to conditionally push some values. Is there a cleaner way of doing this (code below)?

const pushedValues = []; 
if (someArray[0].value) {
    pushedValues.push(x);
}
if (someArray[1].value) {
    pushedValues.push(y);
}
if (someArray[2].value) {
    pushedValues.push(z);
}
...

CodePudding user response:

You can put the values x, y, z into an array and loop over the values with the index.

const pushedValues = []; 
[x, y, z].forEach((val, i)=>{
    if(someArray[i].value) pushedValues.push(val);
});

CodePudding user response:

you can use a forEach like this

const pushedValues = []; 
const data = [x, y, z]
someArray.forEach((v, i) => {
 v.value && pushedValues.push(data[i])
})

CodePudding user response:

You are working with the someArray array. You must first check the values inside an iterative control ( for or while ) and then use the switch-case construct.

Bye M

  • Related