I have an array of conditions
let conditions = [1,3,5,7,9];
let values = [1,2,3,4,5,6,7,8,9,0]
I want
if (values == 1 || values== 3 || values == 5 || values == 7 || values == 9 ){
return values * 3
} else {
return value * 2
}
can someone please help to avoid writing multiple OR Conditions and get this done within 1 statement? Thank you
CodePudding user response:
First of all: you can iterate throught yours values using map
operator
and then check via includes
let conditions = [1,3,5,7,9];
let values = [1,2,3,4,5,6,7,8,9,0]
const result = values.map(val => conditions.includes(val) ? val * 3 : val * 2);
console.log(result)
CodePudding user response:
I'd suggest creating a Set
from your conditions, this will be more efficient for large datasets. You can then use Array.map()
to create your result:
let conditions = new Set([1,3,5,7,9]);
let values = [1,2,3,4,5,6,7,8,9,0]
function getResult(values, conditions) {
return values.map(value => conditions.has(value) ? value * 3: value * 2)
}
console.log('getResult:', getResult(values, conditions));
CodePudding user response:
you can do this:
const toAvoidArray = [1, 3, 5, 7, 9]
if (toAvoidArray.indexOf(value) !== -1) {
return values * 3
} else {
return value * 2
}
or in your case,you can do this:
if (value%2!==0) {
return values * 3
} else {
return value * 2
}