0

I need to get the indexes of the items in question.options array that have 'correct: true' on them. It only returns the first index (because of findIndex), need to retrieve all indexes that match (for questions with more than one answer). I'll then need to add one to each of the indexes for correctAnswerOptions array to pass to another function. Here's my code.

getCorrectAnswers(question: QuizQuestion) {
  console.log(question.options.findIndex(item => item.correct));
  const identifiedCorrectAnswers = question.options.filter(item => item.correct);
  this.numberOfCorrectOptions = identifiedCorrectAnswers.length;

  // need to push the correct answer option numbers here!
  this.correctAnswers.push(identifiedCorrectAnswers);
  // pass the correct answers
  this.setExplanationAndCorrectAnswerMessages(this.correctAnswers);

  return identifiedCorrectAnswers;
}
integral100x
  • 332
  • 6
  • 20
  • 47

4 Answers4

1

function funcWhichNeedCorrectAnswerIndicesPlusOne(indices) {
 console.log(indices)
}

function getCorrectAnswers(question) {
  funcWhichNeedCorrectAnswerIndicesPlusOne(question.options
     .filter(option => option.correct)
     .map(option => question.options.indexOf(option) + 1)
  )   
}

const question = {
 options: [{
   correct: true
  }, {
    correct: false
  }, {
    correct: true
  }
]}

getCorrectAnswers(question)
Vishal Sharma
  • 316
  • 1
  • 8
0

You can use .filter() instead of .findIndex().

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

AzloD
  • 86
  • 4
0

question.options.filter(item => item.correct).map((item, index) => index+1);

Aakash Garg
  • 10,649
  • 2
  • 7
  • 25
0

use the following function, is adapted from this

function getAllIndexes(arr, val) {
    var indexes = [], i;
    for(i = 0; i < arr.length; i++)
        if (arr[i] === val)
            indexes.push(i);
    return indexes;
}