How to check if a JavaScript array contains two 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? By the way, I'm using Lodash in this project.

 


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

You could present your elements as an array, so if you've more than two 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: