Checking if an element exists in an array efficiently and return it I am writing a function for my node/angular app that will prompt the user with a random question that he was not asked before.

To achieve this I wrote this function:

function setQuestion() {
            var q; // question we will eventually ask the user
            for (q in questions) {
                if (!(q._id in questionsUserAlreadyAnswered)) {
                    /* the user has NOT answered this question yet -&gt; so we can ask him now! */
                    $scope.title = q.description;
                    $scope.questionToAsk = q;
                    return;
                }
            }
            /* if we got here it means the user has already answered ALL the questions */
            $scope.title = 'None';
            $scope.questionToAsk = 'None';
}


Here questions is an array of questions (Strings) and so is questionsUserAlreadyAnswered.

I am wondering if this is efficient enough, since I have many questions in the database and the user possibly answered many of them before, so essentially I iterate over all the questions I asked him.(?) twice.
Another way, in addition to the ones Joseph mentioned, you could have a list of questions, and simply remove a question when you ask it.

I.e. something like:

function setQuestion() {
  $scope.question = null;

  if(questions.length) {
    var i = Math.random() * questions.length | 0; // get random index
    $scope.question = questions.splice(i, 1)[0]; // remove question and use it
  }
}


And when the question's answered:

questionsUserAlreadyAnswered.push($scope.question);


This way, you don't need to check multiple arrays.

If you need a "master list", you can do init things like so:

var allQuestions = [...],
    unasweredQuestions = allQuestions.slice(0), // copy array
    answeredQuestions = [];


On another note: Don't use for..in to iterate JavaScript arrays. It doesn't work the same as for..in in other languages. Use a regular for loop or the forEach function.