I’m building a quiz app and I have 2 arrays of objects. I want to obtain another array associating the answers to their question.
How can I do this?
const questions = [{
id: 1,
text: question1
}, {
id: 2,
text: question2
}, {
id: 3,
text: question3
}]
const answers = [{
id: 1,
text: answer1,
questions_id: 1
}, {
id: 2,
text: answer2,
questions_id: 1
}, {
id: 3,
text: answer3,
questions_id: 1
}, {
id: 4,
text: answer4,
questions_id: 1
}...]
I need to get an array with the answers associated to each questions. I know I should use map or filter functions, but I’ve never done it with 2 different arrays comparing one to another. Can anyone help me? thank you.
I tried this but doesn’t work, it return an array of undef:
let answerQuestionId = questions.map((q,a) => {
let temp = answers.find(element => element.domanda_id === q.id)
});
2
Answers
This is how you could combine both arrays into a single one with the corresponding question to each answer using
Array#map
andArray#find
:you can use filter mathod to get associated answer with the questions.