1

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

Abhishek
  • 13
  • 3
  • Hi! you can check doeas value is odd or event like on [this example](https://stackoverflow.com/a/6211660/14135825) – Greg-- Sep 23 '21 at 10:17

3 Answers3

3

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)
shutsman
  • 2,357
  • 1
  • 12
  • 23
0

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));
Terry Lennox
  • 29,471
  • 5
  • 28
  • 40
0

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
}