Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
193
rated 0 times [  196] [ 3]  / answers: 1 / hits: 28716  / 7 Years ago, thu, july 13, 2017, 12:00:00

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);
}

More From » arrays

 Answers
35

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);
}

[#57088] Wednesday, July 12, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ericmaximilianz

Total Points: 252
Total Questions: 118
Total Answers: 87

Location: Virgin Islands (U.S.)
Member since Tue, Jul 7, 2020
4 Years ago
;