I am trying to write a function that compares the values in an array to see if they match a constant "flightValue". However, even when it returns a 'true' value, the loop doesn't stop and ultimately returns an undefined value.
What is the break in my logic here?
// Write a function that takes an integer flightLength (in minutes) and an array of integers movieLengths (in minutes) and returns a boolean indicating whether there are two numbers in movieLengths whose sum equals flightLength.
let moviesArray = [75, 120, 65, 140, 80, 95, 45, 72];
function canWatchTwoMovies(flightLength, array) {
let startIndex = 0;
let endIndex = array.length;
array.forEach((el, index)=> {
let currentPointer = index;
for(i = currentPointer+1; i < endIndex; i++) {
if(array[currentPointer] + array[i] == flightLength) {
// Uncomment the console.log to see that there is a 'true' value
// console.log(array[currentPointer] + array[i] == flightLength);
// Why is this not breaking the loop and returning "true"?
return true;
}
}
});
// I have commented out the default return value
// return false;
console.log("The function doesn't break and always runs to this point");
}
// Should return 'true' for addition of first two elements '75' and '120'
canWatchTwoMovies(195, moviesArray);
Edit: Here is the cleaned up code per Maor Refaeli's reply below:
function canWatchTwoMovies(flightLength, array) {
for (let index = 0; index < array.length; index++) {
let currentPointer = index;
for(let i = currentPointer+1; i < array.length; i++) {
if(array[currentPointer] + array[i] == flightLength) {
return true;
}
}
}
return false;
}