Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logical OR in an Array

Here is where I want to implement my OR

return bigData.country==["US"||"JP"] && (bigData.description=="iPhone 4S")

[ A || B || C || ... ] && [ X || Y || Z ||....]

As you can see above, I am returning objects, if the value of key of object bigData.country is either US or JP, AND bigData.description is either iPhone 4S, can also be more devices.

I'm able to get the desired result, by

return (bigData.country=="US"||bigData.country=="JP") && (bigData.description=="iPhone 4S")

But as I can have convenience to add and remove from an Array, I am trying to use an array. Suggestion to use something different is also welcomed.

If you want to play around with my code here is REPL

like image 743
Dhaval Jardosh Avatar asked Aug 17 '26 17:08

Dhaval Jardosh


2 Answers

You can use Array.prototype.indexOf (to be != -1) like this:

return ["US", "JP"].indexOf(bigData.country) !== -1 && ["X", "Y", "Z"].indexOf(bigData.description) !== -1;

Or in ES6, you can use Array.prototype.includes like:

return ["US", "JP"].includes(bigData.country) && ["X", "Y", "Z"].includes(bigData.description);
like image 114
ibrahim mahrir Avatar answered Aug 19 '26 06:08

ibrahim mahrir


You can use Array#some() method like this:

ES6:

return ['US','JP'].some(val => bigData.country === val) && ['iPhone 4S'].some(v => bigData.description === v);

ES5:

return ['US','JP'].some(function(val){return bigData.country === val}) && ['iPhone 4S'].some(function(v){return bigData.description === v});

Demo:

let bigData = {
  country: 'JP',
  description: 'iPhone 4S'
};

console.log(['US', 'JP'].some(val => bigData.country === val) && ['iPhone 4S'].some(v => bigData.description === v));
like image 29
cнŝdk Avatar answered Aug 19 '26 07:08

cнŝdk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!