javascriptarraysinclude

JavaScript - include() - A check to see if multiple elements are in an array


hope you can help. I've got an empty array in my project which fill up as certain buttons are pressed (using push()). I want to know when a certain set of elements are in the array.

In the below code, it seems to work, the 3 elements are all in the array so it prints 'yes'. If I take out the last element ("TR"), it prints 'nope'. However, if I take out either of the first 2 elements, it prints 'yes'. It seems to be only focusing on the last element in the includes() function.

Is there any way to have the include() or something similar, check to see if all elements are in my array? Keep in mind that the array could have many more elements and they won't be sorted.

Thanks in advance.

var arr = ["TL", "TM", "TR"];

if (arr.includes("TL" && "TM" && "TR")){
    console.log("yes");
} else {
    console.log("nope");
}

Solution

  • The issue is in your if statement because includes() returns a boolean based on the string parameter. A better way of doing this would be to use something like:

    if(arr.includes("TL") && arr.includes("TM") && arr.includes("TR")) {
      console.log("yes");
    }
    

    If you have lots of elements in your array I would suggest something more along the lines of:

    var flag = true;
    for(i=0; i<arr.length; i++) {
      if(!arr.includes(arr[i])) {
        flag = false;
      }
    }
    if(flag) {
      console.log("yes");
    }