For a take-home exercise, I have to write a function that will loop through test answers to check to see if an answer includes a certain String.
checkForPlagarism(submissionsArray, string) takes in an array and a string. It's supposed to loop through all of the objects in the array and check to see if they contain some string. But it seems to only return "false" after the first loop. When I pass in "Metaphase" as the string, for example, it returns "true". If I pass in the exact response of any other questions in the array, it returns "false" even when it should return "true". Here is my REPL: https://repl.it/@clamquarter/Take-Home-Science-Quiz#index.js
What am I doing wrong?
const submissions = [
{
question: 'What is the phase where chromosomes line up in mitosis?',
response: 'Metaphase',
isCorrect: true,
isEssayQuestion: false
}
//and so on...
]
function checkForPlagiarism(submissionsArray, string) {
for (let i = 0; i < submissionsArray.length; i++) {
if (submissionsArray[i].response.includes(string)) {
return true
}
else {
return false
}
}
}
Return statements will exit a for loop. What's happening here is that your loop checks submissionsArray[0]
and evaluates to true
or false
and exits the loop. checkForPlagiarism
returns whatever submissionsArray[0]
evaluated to.
To fix this, remove your else condition and have checkForPlagiarism
return false
when the loop completes.
Here's what that looks like:
function checkForPlagiarism(submissionsArray, string) {
for (let i = 0; i < submissionsArray.length; i++) {
if (submissionsArray[i].response.includes(string)) {
return true
}
}
return false
}