1

I have an array which have all these values that I am trying to compare the var element.

var ALLITEMS = {
  collection: ["item1", "item2", "item3", "item4", "item5", "item6", "item7", "item8"],
  anotherCollection: ["anotheritem1", "anotheritem2", "anotheritem3", "anotheritem4"]
};

Now I am using this:

if(element == "item1" || element =="item2" || element =="item3" || element =="item4" || element =="item5" || element =="item6" || element =="item7") {
  // do something
}
else {
  // do nothing
}

Which works, but How can I shorten this to use the values inside the array ALLITEMS.collection because I have 32 items inside it.

RogerHN
  • 584
  • 1
  • 11
  • 31

2 Answers2

1

Use Array#some.

if (collection.some(v => v == element)){ //returns true if at least one item equals element
  // do something
kind user
  • 40,029
  • 7
  • 67
  • 77
1
if (ALLITEMS.collection.indexOf(element) > -1) {   
    // do something   
}
scottlimmer
  • 2,230
  • 1
  • 22
  • 29