Home > front end >  How do I fix my JavaScript array when it comes back as undefined?
How do I fix my JavaScript array when it comes back as undefined?

Time:04-09

I'm new to JavaScript and can't figure out why my array is coming back as undefined.

Here's my CodePen example: https://codepen.io/TiffSmith126/pen/dyJedWQ

I'm doing an outcome personality quiz that stores the answers in an array, I'm using a function to get the most frequently selected options in the array. However, instead of receiving the result I receive undefined. At this point my function doesn't work because my array is coming back as undefined. Does anyone know how to fix this? Any assistance would be greatly appreciated.

// QUESTIONS

const questions = [
  {
    question: "Question 1",
    answer1: "choice 1",
    answer1Total: "1",
    answer2: "choice 2",
    answer2Total: "2",
    answer3: "choice 3",
    answer3Total: "3"
  },
  {
    question: "Question 2",
    answer1: "choice 1",
    answer1Total: "1",
    answer2: "choice 2",
    answer2Total: "2",
    answer3: "choice 3",
    answer3Total: "3"
  },
  {
    question: "Question 3",
    answer1: "choice 1",
    answer1Total: "1",
    answer2: "choice 2",
    answer2Total: "2",
    answer3: "choice 3",
    answer3Total: "3"
  },
  {
    question: "Question 4",
    answer1: "choice 1",
    answer1Total: "1",
    answer2: "choice 2",
    answer2Total: "2",
    answer3: "choice 3",
    answer3Total: "3"
  },
  {
    question: "Question 5",
    answer1: "choice 1",
    answer1Total: "1",
    answer2: "choice 2",
    answer2Total: "2",
    answer3: "choice 3",
    answer3Total: "3"
  },
  {
    question: "Question 6",
    answer1: "choice 1",
    answer1Total: "1",
    answer2: "choice 2",
    answer2Total: "2",
    answer3: "choice 3",
    answer3Total: "3"
  },
  {
    question: "Question 7",
    answer1: "choice 1",
    answer1Total: "1",
    answer2: "choice 2",
    answer2Total: "2",
    answer3: "choice 3",
    answer3Total: "3"
  },
  {
    question: "Question 8",
    answer1: "choice 1",
    answer1Total: "1",
    answer2: "choice 2",
    answer2Total: "2",
    answer3: "choice 3",
    answer3Total: "3"
  },
  {
    question: "Question 9",
    answer1: "choice 1",
    answer1Total: "1",
    answer2: "choice 2",
    answer2Total: "2",
    answer3: "choice 3",
    answer3Total: "3"
  },
  {
    question: "Question 10",
    answer1: "choice 1",
    answer1Total: "1",
    answer2: "choice 2",
    answer2Total: "2",
    answer3: "choice 3",
    answer3Total: "3"
  }
];

let currentQuestion = 0;
let score = [];
let selectedAnswersData = [];
let scoringData = [];
const totalQuestions = questions.length;

const container = document.querySelector(".quiz-container");
const questionEl = document.querySelector(".question");
const option1 = document.querySelector(".option1");
const option2 = document.querySelector(".option2");
const option3 = document.querySelector(".option3");
const nextButton = document.querySelector(".next");
const previousButton = document.querySelector(".previous");
const restartButton = document.querySelector(".restart");
const result = document.querySelector(".result");

//Function to generate question
function generateQuestions(index) {
  //Select each question by passing it a particular index
  const question = questions[index];
  const option1Total = questions[index].answer1Total;
  const option2Total = questions[index].answer2Total;
  const option3Total = questions[index].answer3Total;
  //Populate html elements
  questionEl.innerHTML = `${index   1}. ${question.question}`;
  option1.setAttribute("data-total", `${option1Total}`);
  option2.setAttribute("data-total", `${option2Total}`);
  option3.setAttribute("data-total", `${option3Total}`);
  option1.innerHTML = `${question.answer1}`;
  option2.innerHTML = `${question.answer2}`;
  option3.innerHTML = `${question.answer3}`;
}

function loadNextQuestion() {
  const selectedOption = document.querySelector('input[type="radio"]:checked');
  //Check if there is a radio input checked
  if (!selectedOption) {
    alert("Please select your answer!");
    return;
  }
  //Get value of selected radio
  const answerScore = Number(
    selectedOption.nextElementSibling.getAttribute("data-total")
  );

  scoringData.push(selectedOption);
  ////Add the answer score to the score array
  score.push(answerScore);

  selectedAnswersData.push();

  function getMostFrequent(scoringData) {
    if (scoringData.length == 0) return null;
    var modeMap = {};
    var maxEl = scoringData[0],
      maxCount = 1;
    for (var i = 0; i < scoringData.length; i  ) {
      var el = score[i];
      if (modeMap[el] == null) modeMap[el] = 1;
      else modeMap[el]  ;
      if (modeMap[el] > maxCount) {
        maxEl = el;
        maxCount = modeMap[el];
      }
    }
    return maxEl;
  }

  const finalScore = getMostFrequent();

  //Finally we incement the current question number ( to be used as the index for each array)
  currentQuestion  ;

  //once finished clear checked
  selectedOption.checked = false;
  //If quiz is on the final question
  if (currentQuestion == totalQuestions - 1) {
    nextButton.textContent = "Finish";
  }
  //If the quiz is finished then we hide the questions container and show the results
  if (currentQuestion == totalQuestions) {
    container.style.display = "none";
    result.innerHTML = `<h1 >Your score: ${finalScore}</h1>
         <div >
            <h1>Summary</h1>
            <p>Possible - Personality Traits, see below for a summary based on your results:</p>
            <p>15 - 21- You Need Help</p>
            <p>10 - 15 - Good Soul</p>
            <p>5 - 10 - Meh </p>
            <p>5 - Are You Even Real</p>
        </div>
        <button >Restart Quiz</button>
         `;
    return;
  }
  generateQuestions(currentQuestion);
}

//Function to load previous question
function loadPreviousQuestion() {
  //Decrement quentions index
  currentQuestion--;
  //remove last array value;
  score.pop();
  //Generate the question
  generateQuestions(currentQuestion);
}

//Fuction to reset and restart the quiz;
function restartQuiz(e) {
  if (e.target.matches("button")) {
    //reset array index and score
    currentQuestion = 0;
    score = [];
    //Reload quiz to the start
    location.reload();
  }
}

generateQuestions(currentQuestion);
nextButton.addEventListener("click", loadNextQuestion);
previousButton.addEventListener("click", loadPreviousQuestion);
result.addEventListener("click", restartQuiz);
html {
  box-sizing: border-box;
}
*,
*:before,
*:after {
  box-sizing: inherit;
}
body {
  margin: 0;
  padding: 0;
  font-family: "Roboto", sans-serif;
  font-weight: 100;
  line-height: 1.7rem;
  background: #000;
}
.quiz-container {
  box-shadow: 1px 1px 1px 1px rgba(0, 0, 0, 0.2);
  text-shadow: 1px 1px white;
  padding: 3rem;
  text-shadow: 0 1px #00000010;
  width: 60%;
  margin: 5rem auto;
  display: flex;
  flex-direction: column;
  background: #000;
  min-height: 100vh;
}
.title {
  margin-top: 0;
  margin-bottom: 3rem;
  color: #f90;
  font-weight: 400;
  font-size: 2.5rem;
  text-align: center;
  text-transform: uppercase;
}
.question {
  margin: 2rem 0;
  font-size: 1.5rem;
  color: #fff;
}
.option {
  padding: 1rem;
  color: #fff;
  background: #f90;
  width: 80%;
  border-radius: 5px;
  transition: all 0.3s;
  margin-bottom: 15px;
}
.option:hover {
  background: #B36B00;
}
.option input:checked .option {
  background: #08038c;
  color: #000;
}
.controls > * {
  margin: 1rem;
}
button {
  padding: 0.5rem 1.5rem;
  border: none;
  box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.1);
  border-radius: 5px;
  font-weight: 300;
  color: white;
  outline: none;
  transform: scale(0.98);
  transition: all 0.2s;
}
button.previous {
  background: #c84630;
}
button.next {
  background: #3c91e6;
}
button.restart {
  background: #0cf574;
  color: #fff;
  font-size: 2rem;
  margin-bottom: 1rem;
  transition: all 0.4s;
}
button.restart:hover {
  color: #fff;
}
button:hover,
button:focus {
  transform: scale(1);
  font-weight: 500;
  box-shadow: 1px 1px 1px rgba(255, 255, 255, 0.5);
}
.result {
  display: flex;
  flex-direction: column;
  padding: 2rem;
  justify-content: center;
  align-items: center;
  text-align: center;
  font-size: 2.5rem;
  min-height: 100vh;
}
.final-score {
  color: #f90;
}
.summary {
  font-size: 1rem;
  text-shadow: 1px 1px #ffffff50;
  color: #f90;
  background: #000;
  border-radius: 5px;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  padding: 0 2rem;
  margin-bottom: 2rem;
}
.summary h1 {
  align-self: center;
}
<head>
    <title>Personality Quiz</title>
    <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
</head>

<body>

    <div >
        <div >Personality Quiz</div>
        <div id="question" ></div>
        <label >
            <input type="radio" name="option" value="1" />
            <span ></span>
        </label>
        <label >
            <input type="radio" name="option" value="2" />
            <span ></span>
        </label>
        <label >
            <input type="radio" name="option" value="3" />
            <span ></span>
        </label>
        <!-- Buttons -->
        <div >
            <button >Previous</button>
            <button >Next</button>
        </div>
    </div>

    <div >

    </div>
</body>

CodePudding user response:

You are executing a function but not passing the argument to it in this line

 const finalScore = getMostFrequent();

change to

 const finalScore = getMostFrequent(scoringData);

CodePudding user response:

you forgot to add scoringData to const finalScore = getMostFrequent();

// QUESTIONS

const questions = [
  {
    question: "Question 1",
    answer1: "choice 1",
    answer1Total: "1",
    answer2: "choice 2",
    answer2Total: "2",
    answer3: "choice 3",
    answer3Total: "3"
  },
  {
    question: "Question 2",
    answer1: "choice 1",
    answer1Total: "1",
    answer2: "choice 2",
    answer2Total: "2",
    answer3: "choice 3",
    answer3Total: "3"
  },
  {
    question: "Question 3",
    answer1: "choice 1",
    answer1Total: "1",
    answer2: "choice 2",
    answer2Total: "2",
    answer3: "choice 3",
    answer3Total: "3"
  },
  {
    question: "Question 4",
    answer1: "choice 1",
    answer1Total: "1",
    answer2: "choice 2",
    answer2Total: "2",
    answer3: "choice 3",
    answer3Total: "3"
  },
  {
    question: "Question 5",
    answer1: "choice 1",
    answer1Total: "1",
    answer2: "choice 2",
    answer2Total: "2",
    answer3: "choice 3",
    answer3Total: "3"
  },
  {
    question: "Question 6",
    answer1: "choice 1",
    answer1Total: "1",
    answer2: "choice 2",
    answer2Total: "2",
    answer3: "choice 3",
    answer3Total: "3"
  },
  {
    question: "Question 7",
    answer1: "choice 1",
    answer1Total: "1",
    answer2: "choice 2",
    answer2Total: "2",
    answer3: "choice 3",
    answer3Total: "3"
  },
  {
    question: "Question 8",
    answer1: "choice 1",
    answer1Total: "1",
    answer2: "choice 2",
    answer2Total: "2",
    answer3: "choice 3",
    answer3Total: "3"
  },
  {
    question: "Question 9",
    answer1: "choice 1",
    answer1Total: "1",
    answer2: "choice 2",
    answer2Total: "2",
    answer3: "choice 3",
    answer3Total: "3"
  },
  {
    question: "Question 10",
    answer1: "choice 1",
    answer1Total: "1",
    answer2: "choice 2",
    answer2Total: "2",
    answer3: "choice 3",
    answer3Total: "3"
  }
];

let currentQuestion = 0;
let score = [];
let selectedAnswersData = [];
let scoringData = [];
const totalQuestions = questions.length;

const container = document.querySelector(".quiz-container");
const questionEl = document.querySelector(".question");
const option1 = document.querySelector(".option1");
const option2 = document.querySelector(".option2");
const option3 = document.querySelector(".option3");
const nextButton = document.querySelector(".next");
const previousButton = document.querySelector(".previous");
const restartButton = document.querySelector(".restart");
const result = document.querySelector(".result");

//Function to generate question
function generateQuestions(index) {
  //Select each question by passing it a particular index
  const question = questions[index];
  const option1Total = questions[index].answer1Total;
  const option2Total = questions[index].answer2Total;
  const option3Total = questions[index].answer3Total;
  //Populate html elements
  questionEl.innerHTML = `${index   1}. ${question.question}`;
  option1.setAttribute("data-total", `${option1Total}`);
  option2.setAttribute("data-total", `${option2Total}`);
  option3.setAttribute("data-total", `${option3Total}`);
  option1.innerHTML = `${question.answer1}`;
  option2.innerHTML = `${question.answer2}`;
  option3.innerHTML = `${question.answer3}`;
}

function loadNextQuestion() {
  const selectedOption = document.querySelector('input[type="radio"]:checked');
  //Check if there is a radio input checked
  if (!selectedOption) {
    alert("Please select your answer!");
    return;
  }
  //Get value of selected radio
  const answerScore = Number(
    selectedOption.nextElementSibling.getAttribute("data-total")
  );

  scoringData.push(selectedOption);
  ////Add the answer score to the score array
  score.push(answerScore);

  selectedAnswersData.push();

  function getMostFrequent(scoringData) {
    if (scoringData.length == 0) return null;
    var modeMap = {};
    var maxEl = scoringData[0],
      maxCount = 1;
    for (var i = 0; i < scoringData.length; i  ) {
      var el = score[i];
      if (modeMap[el] == null) modeMap[el] = 1;
      else modeMap[el]  ;
      if (modeMap[el] > maxCount) {
        maxEl = el;
        maxCount = modeMap[el];
      }
    }
    return maxEl;
  }

  const finalScore = getMostFrequent(scoringData);

  //Finally we incement the current question number ( to be used as the index for each array)
  currentQuestion  ;

  //once finished clear checked
  selectedOption.checked = false;
  //If quiz is on the final question
  if (currentQuestion == totalQuestions - 1) {
    nextButton.textContent = "Finish";
  }
  //If the quiz is finished then we hide the questions container and show the results
  if (currentQuestion == totalQuestions) {
    container.style.display = "none";
    result.innerHTML = `<h1 >Your score: ${finalScore}</h1>
         <div >
            <h1>Summary</h1>
            <p>Possible - Personality Traits, see below for a summary based on your results:</p>
            <p>15 - 21- You Need Help</p>
            <p>10 - 15 - Good Soul</p>
            <p>5 - 10 - Meh </p>
            <p>5 - Are You Even Real</p>
        </div>
        <button >Restart Quiz</button>
         `;
    return;
  }
  generateQuestions(currentQuestion);
}

//Function to load previous question
function loadPreviousQuestion() {
  //Decrement quentions index
  currentQuestion--;
  //remove last array value;
  score.pop();
  //Generate the question
  generateQuestions(currentQuestion);
}

//Fuction to reset and restart the quiz;
function restartQuiz(e) {
  if (e.target.matches("button")) {
    //reset array index and score
    currentQuestion = 0;
    score = [];
    //Reload quiz to the start
    location.reload();
  }
}

generateQuestions(currentQuestion);
nextButton.addEventListener("click", loadNextQuestion);
previousButton.addEventListener("click", loadPreviousQuestion);
result.addEventListener("click", restartQuiz);
html {
  box-sizing: border-box;
}
*,
*:before,
*:after {
  box-sizing: inherit;
}
body {
  margin: 0;
  padding: 0;
  font-family: "Roboto", sans-serif;
  font-weight: 100;
  line-height: 1.7rem;
  background: #000;
}
.quiz-container {
  box-shadow: 1px 1px 1px 1px rgba(0, 0, 0, 0.2);
  text-shadow: 1px 1px white;
  padding: 3rem;
  text-shadow: 0 1px #00000010;
  width: 60%;
  margin: 5rem auto;
  display: flex;
  flex-direction: column;
  background: #000;
  min-height: 100vh;
}
.title {
  margin-top: 0;
  margin-bottom: 3rem;
  color: #f90;
  font-weight: 400;
  font-size: 2.5rem;
  text-align: center;
  text-transform: uppercase;
}
.question {
  margin: 2rem 0;
  font-size: 1.5rem;
  color: #fff;
}
.option {
  padding: 1rem;
  color: #fff;
  background: #f90;
  width: 80%;
  border-radius: 5px;
  transition: all 0.3s;
  margin-bottom: 15px;
}
.option:hover {
  background: #B36B00;
}
.option input:checked .option {
  background: #08038c;
  color: #000;
}
.controls > * {
  margin: 1rem;
}
button {
  padding: 0.5rem 1.5rem;
  border: none;
  box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.1);
  border-radius: 5px;
  font-weight: 300;
  color: white;
  outline: none;
  transform: scale(0.98);
  transition: all 0.2s;
}
button.previous {
  background: #c84630;
}
button.next {
  background: #3c91e6;
}
button.restart {
  background: #0cf574;
  color: #fff;
  font-size: 2rem;
  margin-bottom: 1rem;
  transition: all 0.4s;
}
button.restart:hover {
  color: #fff;
}
button:hover,
button:focus {
  transform: scale(1);
  font-weight: 500;
  box-shadow: 1px 1px 1px rgba(255, 255, 255, 0.5);
}
.result {
  display: flex;
  flex-direction: column;
  padding: 2rem;
  justify-content: center;
  align-items: center;
  text-align: center;
  font-size: 2.5rem;
  min-height: 100vh;
}
.final-score {
  color: #f90;
}
.summary {
  font-size: 1rem;
  text-shadow: 1px 1px #ffffff50;
  color: #f90;
  background: #000;
  border-radius: 5px;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  padding: 0 2rem;
  margin-bottom: 2rem;
}
.summary h1 {
  align-self: center;
}
<head>
    <title>Personality Quiz</title>
    <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
</head>

<body>

    <div >
        <div >Personality Quiz</div>
        <div id="question" ></div>
        <label >
            <input type="radio" name="option" value="1" />
            <span ></span>
        </label>
        <label >
            <input type="radio" name="option" value="2" />
            <span ></span>
        </label>
        <label >
            <input type="radio" name="option" value="3" />
            <span ></span>
        </label>
        <!-- Buttons -->
        <div >
            <button >Previous</button>
            <button >Next</button>
        </div>
    </div>

    <div >

    </div>
</body>

  • Related