4

Above code splices only first element it doesn't work second time in for loop! Please help!

var answeredQuestions = [18,19];
var questions = [{"questionid":"18"},{"questionid":"19"},{...}];

for (var j = 0; j < questions.length; j++) {
    var pos = $.inArray(parseInt(questions[j].questionid), answeredQuestions);
    if(parseInt(pos) != -1) {
        questions.splice(j,1);
    }
}

2 Answers 2

5

When you modify the array (remove items from it) in the middle of the for loop, it causes your for loop to miss items in the array.

One way to work-around that is to process the array backwards (from end to front) so that when you remove the current item from the array, you aren't messing up any of the indexes in the next iterations of the for loop.

var answeredQuestions = [18,19];
var questions = [{"questionid":"18"},{"questionid":"19"},{...}];

for (var j = questions.length - 1; j >= 0; j--) {
    var pos = $.inArray(parseInt(questions[j].questionid, 10), answeredQuestions);
    if(pos !== -1) {
        questions.splice(j,1);
    }
}

Also, there is no need to use parseInt() on the result of $.inArray as it is already an integer.


Edit as of 2015/2016, it's probably easier to use .filter() and let that method handle the modifying of the array for you:

var answeredQuestions = [18,19];
var questions = [{"questionid":"18"},{"questionid":"19"},{...}];
questions = questions.filter(function(item) {
    // keep only questions that haven't been answered already
    return answeredQuestions.indexOf(+item.questionid) === -1;
});
Sign up to request clarification or add additional context in comments.

4 Comments

ohh! didnt thought of that! perfect! let me try that out!
@jayshahagile - suggestion added.
'j' should decrement don't you think senor?
@jayshahagile - yep, decrement. Edited.
0

What you want to do is just filter the answered questions. You could use .filter:

var answeredQuestions = [18,19];
var questions = [{"questionid":"18"},{"questionid":"19"},{...}];

var result = questions.filter(function(e) {
  return answeredQuestions.indexOf(+e.questionid) == -1;
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.