Zauber Zauber - 1 month ago 7
Javascript Question

I have two arrays which contain other arrays. How can I compare each nested array in array1 with its counterpart in array2?

Sorry if my title is confusing, this is difficult to explain.

I have created a multiple choice exam. When a user submits the exam, the answers are collected and put in an array like so:

userSubmittedAnswers = [
['c'], // Q.1
['d'], // Q.2
['a', 'b', 'c', 'd'], // Q.3
['b'], // Q.4
['c', 'd'], // Q.5
['d'], // Q.6
]


Each array inside this array called answers contains the submitted answer for each question in the multiple choice. Some answers have more than 1 available answer so that's why question 3 and 5 for example have more than 1 value.

This array is sent to the server where I want to compare it to a similar array which has the Correct answers:

correctAnswers = [
['d'], // Q.1
['d'], // Q.2
['a', 'b', 'c'], // Q.3
['b'], // Q.4
['c', 'd'], // Q.5
['d'], // Q.6
]


What I want to achieve is comparing the submitted answers with the correct answers, but to make sure that I count how many of the nested arrays are incorrect and keep track of them so that I can highlight them to the user on the client. I'm not sure what the best way to do this is... Any advice much appreciated

Answer

You could use reduce() and every() and return object with incorrect answers and total number of incorrect answers.

var userSubmittedAnswers = [
  ['c'], // Q.1
  ['d'], // Q.2
  ['a', 'b', 'c', 'd'], // Q.3
  ['b'], // Q.4
  ['c', 'd'], // Q.5
  ['d'], // Q.6
]

var correctAnswers = [
  ['d'], // Q.1
  ['d'], // Q.2
  ['a', 'b', 'c'], // Q.3
  ['b', 'a'], // Q.4
  ['c', 'd'], // Q.5
  ['d'], // Q.6
]


//Loop SubmittedAnswers array (result, currentElement, index)
var result = userSubmittedAnswers.reduce(function(r, e, i) {
  //First check if both array with same index are equal in length if they are continue with every check else return false.
  var check = (e.length == correctAnswers[i].length) ? true : false;
  //Loop current element or array or e with every() that will return true or false if every element is found in element with same index inside correctAnswers array
  if (check) {
    check = e.every(function(a) {
      return correctAnswers[i].indexOf(a) != -1;
    });
  }
  //If check return false add that Q+(index+1) to incorrect array and increment total incorrect answers
  if (!check) {
    r.incorrect = (r.incorrect || []).concat('Q.' + (i + 1));
    r.total = (r.total || 0) + 1;
  }
  return r;
}, {})

console.log(result)