-1

I want to be able to check if a string is equal to any of the strings inside an array. I know you can check multiple parameters like so:

let value = 'sales';

if ( value == 'sales' || value == 'broker' ){}

But I need to use an array like:

let value = 'sales';
let array = ['sales', 'broker'];

if ( value == array ){}

How can I do this?

Reece
  • 2,581
  • 10
  • 42
  • 90
  • 1
    look for the index of the value in the array with `array.indexOf(value)`. It'll return `-1` if it's not found, or an index if it is. Note that `.includes()` might cause problems in Internet Explorer. – Gavin Apr 20 '20 at 15:41
  • [].includes(value) .. [].some(x=>test(x)) .. `~[].indexOf(element)` – Estradiaz Apr 20 '20 at 15:42

5 Answers5

3

Use array.includes:

if (array.includes(value)) {
    ...
}
Ben
  • 3,160
  • 3
  • 17
  • 34
0

You use array includes which returns a Boolean

let array = ['sales', 'broker'];

function test( value ) {
  if ( array.includes(value) ){
    console.log('true', value)
  } else {
    console.log('false', value)
  }
}

test('sales')
test('world')
epascarello
  • 204,599
  • 20
  • 195
  • 236
0

You can also use filter function, which might be better especially if you later need some additional checks.

if(array.filter(el => el === value).length > 0){
  //
}
Asqan
  • 4,319
  • 11
  • 61
  • 100
0

You can use includes method to check if array contains a value.

let array = ['sales', 'broker'];
    
console.log(array .includes('sales'));
0

use includes method

if (array.includes(value)) { }

Chandra Sekar
  • 302
  • 1
  • 13