简体   繁体   中英

How do i push an array[i] to another array

Basically i have to create a quiz with 3category. each with 5questions. I would have to push the selected category-questions into this new array from the array with all the questions. I am unable to do so.

pushSelectedQuestion() {
    for (var i = 0; i < this.getNumberOfQuestion; i++) {
        if (usercategory == questionPool[i].category) {
            mcqSelected.push(questionPool[i])
            return mcqSelected;
        }
    }

}

usercategory = input from user. if user chooses category 1. if (1 == questionPool[1].category) (if it matches the category) then it will be pushed.

This is the part which i cant do

Well, from the information you've provided, there's one main issue here - the return statement is definitely shortcutting the loop - so even if you have everything else right, you'll only ever get the first matching question. The rest will have been cut out by the return statement, which stops the function and returns the value.

pushSelectedQuestion() {
    for (var i = 0; i < this.getNumberOfQuestion; i++) {
        if (usercategory == questionPool[i].category) {
            mcqSelected.push(questionPool[i])
           // the below line is causing this loop to end after the first time through the list. 
           // Remove it and then put a console.log(mcqSelected); 
           // here instead to see the value during each iteration of the loop.  
                    return mcqSelected;
                }
            }

}

There are a lot of ways to accomplish what you want to do here though. For example, you could just use the javascript Array.filter method like so

let selectedQuestions = questionPool.filter(question => question.category == userCategory)

Maybe I am not understanding your question correctly, but can't you use nested arrays. If the questions are categorized beforehand that is.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM