How to check if a JavaScript array contain 2 specific values only

  • A+
Category:Languages

I need to check if an array includes two values and only them.

This is my ugly solution for now:

if (myArray.includes('foo') && myArray.includes('bar') && myArray.length === 2) {     // do something } 

Update:

I may have to check three or more values as well. Any elegant solution (I'm already using lodash in this project) ?

Thank you!

 


I may have to check three or more values as well.

You could present you elements as an array, so if you've more than 2 items to check, the condition will still short and the same, using .every() method like :

myArray.every(elem => [1,2].indexOf(elem) > -1) 
var myArray = [2, 1]; var myItems = [1, 2];  if (myArray.length === myItems.length && myArray.every(elem => myItems.indexOf(elem) > -1)) {   console.log('PASS'); }

UPDATE:

Since you're using lodash, you could simply use _.difference() like :

if( _.size(myArray) === _.size(myItems) && _.difference(myArray, myItems).length === 0 ) {     // do something } 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: