0

I have a ternary operator which sees if values in an array are the same as my targeted value. Is there an easy way to do what I'm trying to do to save me a lot of time and hard coding in array indexes. Is there a way to not use a lot of or operator?

I essentially have a long list of array indexes to compare against like this:

(price[0] === this.props.result.cost ||
 price[1] === this.props.result.cost ||
 price[2] === this.props.result.cost ||
 price[3] === this.props.result.cost ||
 price[4] === this.props.result.cost ) 
? this 
: that

I feel like there is something basic that I'm missing or some other way completely to make this an easier task to do.

  • 1
    If you want to check the array contains the value: `price.includes(this.props.result.cost) ? this : that` If you want to check only the first 5 indices `price.slice(0, 5).includes(this.props.result.cost) ? this : that` – adiga Oct 23 '19 at 10:36
  • @adiga thanks for that. Sorry for the basic question and duplicate. – Ashley Bennett Oct 23 '19 at 10:52

1 Answers1

1

If you are checking for primitives (integers, strings) in your array, then Array.prototype.includes is the simplest choice. It also successfully determines the presence of NaN in the array:

const price = [1, 2, 'str', 3, NaN, {'foo': 'bar'}];

//true
console.log(price.includes(3));
//true
console.log(price.includes('str'));
//true
console.log(price.includes(NaN));
//false
console.log(price.includes({'foo': 'bar'}));
In the above snippet all except the check for the object returns true, in case of object the reference is not the same so it returns false.

You can use Array.prototype.some for the test checking the presence of a particular attribute of an object:

const price = [1, 2, 'str', 3, 4, NaN, {'foo':'bar'}, 5];

let cost = 5;
//true
console.log(price.some((obj) => obj === cost));

//for checking if there is an object in the arrray with the attribute value 'foo' which has the value 'bar'

cost = 'bar';
//true
console.log(price.some((obj) => obj.foo == cost));

Or a ES6 Set can be used for constant time lookup, if the input array is big enough:

 const price = [1, 2, 3, 4, 5];

const cost = 5;

console.log(new Set(price).has(cost));
Fullstack Guy
  • 16,368
  • 3
  • 29
  • 44