Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Roland O'Donnell
5,667 Pointswhy won't this or any slight variance of this work? I'm bedazzled
var x = [1,2];
var y = [1,2];
if (x[0] && x[1] == y[0] && y[1] ) {
print("You have Won LOTTO!!!");
} else {
print("waste of money idiot!!");
}
2 Answers
Thomas Nilsen
14,957 PointsThere are multiple ways you can check if two arrays are equal.
First, you can convert both of them to a string, and then compare:
console.log(x.toString() === y.toString()); //true
or you can make a function where you loop through the array and compare each element to each other:
function arraysEqual(arr1, arr2) {
if(arr1.length !== arr2.length)
return false;
for(var i = arr1.length; i--;) {
if(arr1[i] !== arr2[i])
return false;
}
return true;
}
console.log(arraysEqual(x, y)); //true
Or, to do what you (almost) did:
if(x[0] === y[0] && x[1] === y[1]) {
console.log("You have Won LOTTO!!!"); //This will print
} else {
console.log("waste of money idiot!!");
}
Jason Anello
Courses Plus Student 94,610 PointsYou're probably going to be better off with the function solution and examining each element.
The .toString() method is going to lead to incorrect results for certain arrays.
Consider the following 2 examples:
console.log(["cat,dog"].toString() === ["cat", "dog"].toString()); // true
console.log([1, 2].toString() === ["1", "2"].toString()); // true
They are both true even though the arrays are not the same.
Roland O'Donnell
5,667 Pointsthank you, just so understand something else, whenever a function hits a return statement it exits the function? is that correct? so if the arrays are not the same length it will return false and exits the function with out ever running the rest of the function?
thanks again again for your help!
Thomas Nilsen
14,957 PointsThat is correct :) If the arrays is not of equal length - then we know for sure that the arrays cannot be equal and we end the function there.
Roland O'Donnell
5,667 PointsRoland O'Donnell
5,667 Pointsall i want to do is know how to compare two arrays to see if they are the same..thanks