I have an array in which i want to conditionally push some values. Is there a cleaner way of doing this (code below)?
JavaScript
x
12
12
1
const pushedValues = [];
2
if (someArray[0].value) {
3
pushedValues.push(x);
4
}
5
if (someArray[1].value) {
6
pushedValues.push(y);
7
}
8
if (someArray[2].value) {
9
pushedValues.push(z);
10
}
11
12
Advertisement
Answer
You can put the values x, y, z
into an array and loop over the values with the index.
JavaScript
1
5
1
const pushedValues = [];
2
[x, y, z].forEach((val, i)=>{
3
if(someArray[i].value) pushedValues.push(val);
4
});
5