I have an object in a quiz application that stores the question number and the user answer. I have a function that loops through the object to check if the question number exists in the object. If it does the user answer is updated and if not a new entry is made.
My problem is the for the first entry I can add, check if question number exists and update user answers but for all other entries it fails to match the question number so all updates appear as new entries in the object.
This is my debug output:
0: {questionNo: 0, answer: Array(2)}
1: {questionNo: 2, answer: Array(2)}
2: {questionNo: 2, answer: Array(2)}
There should only be one entry of 2 in question number (questionNo) as the function should check if the question number already exists and update array would be. The function only works with the data in index 0 and all others question numbers are not matched and become new entries.
The function is:
public answers: any = [];
public count = 0;
constructor(){
}
addItem(item, item2){
this.answers.push({
questionNo: item,
answer: item2
});
}
checkIfQnAnswered(num){
for(let i = 0; i < this.answers.length; i++)
{
//console.log(i);
if(this.answers[i].questionNo == num)
{
console.log("Question number exists at " + i);
//this.count++;
//return this.count;
return true;
}
else if(this.answers[i].questionNo != num)
{
console.log("Question number does not exisit");
//this.count++;
//return this.count;
return false;
}
}
}
updateQnAnswered(item, item2){
for(let i = 0; i < this.answers.length; i++)
{
if(this.answers[i].questionNo == item)
{
// this.count++;
//this.answers.splice(i, 1);
this.answers[i].questionNo = item;
this.answers[i].answer = item2;
}
}
}
The following code should work. The problem with your code was that, when it was index 0, there was no match. So the if
condition was false and else if
becomes true. Next the code in else if
block executes and immediately returns (this breaks the loop, stops the function execution and returns false
). So the loop runs only one time for the example provided. Actually, the loop will run only one time for any value of num
and this.answers
, as the if-else ladder is exhaustive and both have return
statement in them.
checkIfQnAnswered(num) {
for(let i = 0; i < this.answers.length; i++) {
if(this.answers[i].questionNo === num) {
// found first match, now return true
console.log("Question number exists at " + i);
//this.count++;
//return this.count;
return true;
}
}
// we are here, means no match was found
return false
}
In the above code, the functions return true
when the loop finds first match; false
otherwise when there is no match.