Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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");
}
like image 412
JordiLaForge Avatar asked Jul 13 '17 20:07

JordiLaForge


People also ask

How do you search multiple values in an array?

If you want to find the duplicates as well, you can first make a pass with array_unique, then iterate over that array using array_keys on the original; anything which returns an array of length > 1 is a duplicate, and the result is the keys in which the duplicates are stored.

How do you check if an array contains an array JavaScript?

You can use the includes() method in JavaScript to check if an item exists in an array. You can also use it to check if a substring exists within a string. It returns true if the item is found in the array/string and false if the item doesn't exist.

How do you check if an array includes elements of another array?

Use the inbuilt ES6 function some() to iterate through each and every element of first array and to test the array. Use the inbuilt function includes() with second array to check if element exist in the first array or not. If element exist then return true else return false.

How do I check if an array contains all elements?

You can try with Array. prototype. every() : The every() method tests whether all elements in the array pass the test implemented by the provided function.


2 Answers

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");
}
like image 78
brian Avatar answered Oct 21 '22 06:10

brian


Even though the above answers show methods to get your desired result, I'm surprised no one has addressed why your original attempt didn't work. This gets into some foundational rules that JavaScript follows: how functions are called, logical operator evaluation, and operator precedence.

Calling arr.includes()

First off, you have a function includes which takes a single string argument. You have given this argument an expression instead of a string, so it is going to evaluate the expression. If the evaluation produces a string, it will return that value. If it produces a different type, it will attempt to convert the result to a string. So to clear it up, you haven't given it 3 strings to look for, but one expression that will be evaluated and become the string you are looking for.

Logical Operator Evaluation

But what is the value of that string? In JavaScript, the logical operators work in a way that can shortcut and return one of the values being evaluated. In most cases, we'd be comparing boolean values, and get true or false from the evaluation, but we're working with strings here, not booleans. Strings in JavaScript can be evaluated as "truthy" or "falsy", the former being any string that has length and the latter being a string with no length (an empty string). With this in mind, the shortcut functionality of the logical AND && operator will look at the first value in the expression, and if that value is "falsy" it will return that value. If that value is "truthy" it will look at the other side of the expression and return its value.

MDN describes this logic pretty well. Given expr1 && expr2 here's the logic:

Returns expr1 if it can be converted to false; otherwise, returns expr2. Thus, when used with Boolean values, && returns true if both operands are true; otherwise, returns false.

Order Precendence

Finally, a note on order precedence. Logical AND && is of equal precendence to itself, so your expression will read from left-to-right. If, say, your expression was "TL" || "TM" && "TR" the "TM" && "TR" expression would be evaluated first since logical AND && has a higher precendence than logical OR ||.

Evaluating Your Expression

Knowing all of this, we can pick apart what your expression is doing:

"TL" && "TM" && "TR" is comprised of all logical AND operators, so we will read this from left-to-right, starting with "TL" && "TM". Since "TL" is a truthy string, the other side of the expression is returned which is "TM". The next expression is then "TM" && "TR", of which "TM" is a truthy value, so "TR" is returned. In the end, the includes function is checking if the value of "TR" exists in the array, and ultimately returns true.

Again, do mark one of the others as answers here. Looping through the values you want to search for in the array is what you're looking for, and writing your own loop or using reduce accomplishes that, but I wanted to explain why your initial attempt probably seemed odd and clear up just what was happening.

like image 28
Jonathan Michalik Avatar answered Oct 21 '22 04:10

Jonathan Michalik