Skip to content
Advertisement

How to shorten multiple if statements (not if else)

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);
}
...

Advertisement

Answer

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);
});
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement