I am trying to compare these two arrays and if their content is the same with the same order, temp should return true, if they don’t match, temp should return false.
if(selectedKeysList == myCombination){
temp = true;
}else{
temp = false;
}
In the console this comparison reads as follow:
myCombination: 7,8,8,8
selectedKeysList: 7,8,8,8
So I know that they have the same numbers with the same order. The problem is that temp still returns always false!
Could anyone tell me what is wrong here? Why although both arrays has the same numbers and order, temp still false?
You’re not comparing the content, you’re comparing the variables to each other, and since they point to different arrays, they can’t be equal regardless of the contents. You can use SequenceEqual in Linq.
As Eric said, you can use Linq to compare them. Arrays are reference types so when you are checking equality, you’re actually checking to see if the variables point to the same object in memory, not the same values. If you want an easy comparison without using LINQ you can do the following:
//No reason to enumerate if the length is different
if(myCombination.length != selectedKeysList.length)
return false;
for(var i = 0; i < myCombination.length; i++)
{
//If we find values at any point that don't match, return false
if(myCombination[i] != selectedKeysList[i])
return false;
}
//If we've made it this far, the lengths match and all values match
return true;
Thank you for your replies! So instead of comparing for true I should compare them for false, interesting! You see when I used a for loop comparing the values inside and the position of those values, it was returning true if they were right, but also if some of the value match it.
Linq only work with enumerator right? so I would have to change the whole script for that.
I will try the approach that Dustin proposed. I didn’t think about that.
Ok I tried this way and still when I test pressing on key wrong but the other right it prints both outcomes. It is like if it is not stopping when it finds different values! I pasted that part of the code that has to do with the whole thing to see if you find what is wrong.
It works with IEnumerable sequences, such as arrays as lists. I don’t know why you’d have to change anything, just import the Linq namespace and use SequenceEqual. I’d strongly recommend using what’s already in Unity rather than trying to reinvent the wheel and writing unnecessary code.
Eric5h5, I went to the msdn library and I can’t find any example for the use of SequenceEqual on js. Could you give me an idea of how I can use this SequenceEqual to compare my two arrays in js?