mardi 13 octobre 2020

How to push to multi-dimensional array if value does not exist in javascript

I have a multi-dimensional array that stores information on questions and answers given by a user and relies on 3 checks.

  • if the array is empty it pushes the initial data set
  • if a question number exists in the array, its associated answer is updated
  • if a question number does not exist, the question information and answer are pushed to the array

I have managed to do the first 2 checks, but I am having trouble with the third check. When I try to push new question & answer information it pushes multiple repetitions instead of just one data set.

The function I am using is:

getBoolvalue(boolvalue, optionIndex, questionnNumber, option)
{
    if(this.answerboolvalues[0] == null)
    {
        this.answerboolvalues.push([questionnNumber, optionIndex, option, boolvalue]);
        console.log(this.answerboolvalues);
    
    }
    else
    {
        console.log("Array length : " + this.answerboolvalues.length);
        console.log("Array item : " + this.answerboolvalues[1][2]);
    
        for(let j = 0; j < this.answerboolvalues.length; j++)
        {
            if(this.answerboolvalues[j][0] == questionnNumber)  
            {
                if(this.answerboolvalues[j][1] == optionIndex)
                {
                    this.answerboolvalues[j][3] = boolvalue;
                    console.log(this.answerboolvalues);
                }
            }
            else if(this.answerboolvalues[j][0] != questionnNumber) 
            {
                this.answerboolvalues.push([questionnNumber, optionIndex, option, boolvalue]);
            }
        }
    }

}

Aucun commentaire:

Enregistrer un commentaire