Reputation: 187
My objective is to compare the two arrays. I can't get it return false, it just compares the first values and returns. Am I not asking it correctly to loop through all values before determining true or false?
var array1 =[1,2,3];
var array2=[1,2,4];
var areArraysSame = function(array1, array2) {
if(array1.length !== array2.length) {
return "These are not the same length";
}
for(var i = 0; i <= array1.length; i++) {
if(array1[i] !== array2[i]) {
return "These are not the same array";
}else{
return "these are the same array";
}
}
};
console.log(areArraysSame(array1, array2));
Upvotes: 0
Views: 1925
Reputation: 477
You have a return statement in the first iteration of your for loop; after the first item in each array is compared your loop will end whether it's true or false.
You can store a condition and base your return on that.
var array1 = [1, 2, 3];
var array2 = [1, 2, 4];
var areArraysSame = function (array1, array2) {
var isSame = true;
if (array1.length !== array2.length) {
return "These are not the same length";
}
for (var i = 0; i <= array1.length; i++) {
if (array1[i] !== array2[i]) {
isSame = false;
}
}
return isSame ? "These are the same array" : "These are not the same array";
};
console.log(areArraysSame(array1, array2));
Upvotes: 0
Reputation: 3266
You are returning immediately after checking the first value, remove the else block in the for loop such that it compares all the values as shown below :
var array1 =[1,2,3];
var array2=[1,2,4];
var areArraysSame = function(array1, array2) {
if(array1.length !== array2.length) {
return "These are not the same length";
}
for(var i = 0; i <= array1.length; i++) {
if(array1[i] !== array2[i]) {
return "These are not the same array";
}
}
return "These are the same array";
};
console.log(areArraysSame(array1, array2));
Upvotes: 1
Reputation: 288
Return will stop your loop and exit the function. So since in the above code your first element for both arrays is 1 the code returns on the first iteration of the loop. If you want to return whether or not the arrays match return after the loop and use a boolean variable to keep track of whether or not the arrays match. Only return in the loop on a false statement.
Upvotes: 0
Reputation: 8291
You are not waiting for all comparisons to take place before returning true
(or your true string)
You should do this:
for(var i = 0; i <= array1.length; i++) {
if(array1[i] !== array2[i]) {
return false;
}
}
return true;
Wait for the loop to end before returning true
Upvotes: 2