0
I have two arrays:
The first has some questions, ex:
Array questions:
[
{
"id": 2,
"question": "Questão 1:",
"essay_question": false,
"value": "2.00"
},
{
"id": 3,
"question": "Questão 2:",
"essay_question": false,
"value": "1.00"
},
{
"id": 4,
"question": "Questão 3:",
"essay_question": false,
"value": "1.00"
}
]
And the second has the choices options for the above issues:
Array options:
[
{
"id": 1,
"option": "Opção A",
"correct": false,
"question_id": 2
},
{
"id": 4,
"option": "Opção B",
"correct": true,
"question_id": 2
},
{
"id": 6,
"option": "Opção A",
"correct": false,
"question_id": 3
},
{
"id": 7,
"option": "Opção B",
"correct": true,
"question_id": 3
},
{
"id": 9,
"option": "Opção A",
"correct": false,
"question_id": 4
},
{
"id": 12,
"option": "Opção B",
"correct": true,
"question_id": 4
}
]
I need to create a new array by joining these two together as follows: Comparing the issue ID with the option id and include the options within the question array.
Ex:
[
{
id: 2,
question: 'Questão 1:',
essay_question: false,
value: '2.00',
options: [
{
id: 1,
option: 'Opção A',
correct: false,
question_id: 2,
},
{
id: 4,
option: 'Opção B',
correct: true,
question_id: 2,
},
],
},
];
I’m trying to do it this way:
const questions = question.map((q) => {
if (options.filter((opt) => opt.question_id === q.id))
return { ...q.dataValues, options: opt.dataValues };
return { ...q.dataValues, options: null };
});
The map and filter worked, the problem is time to put the array options found inside the array questions. I am receiving error: "'opt' is not defined."
The block of
if
inif (options.filter((opt) => opt.question_id === q.id)) { ... }
always run pq the methodArray.prototype.filter
at all times returns an array (which is a value Truthy in Javascript, which allows entry into the conditional in question). In addition, you statedopt
as a parameter of the predicate passed tofilter
, which causes the subsequent error to which you refer. The code, if corrected, works, although I can count on some improvements to performance, since currently has complexityO(m * n)
where q could beO(m + n)
.– Luiz Felipe
I understood the issue of opt being outside the scope. I just didn’t understand the issue of complexity O(M * n), The code you suggested worked.
– Fred
It’s because for every item of
questions
, you make afilter
inoptions
completely, that is, it will scan the arrayoptions
n
times beingn
the number of elements ofquestions
. Thus, ifquestions
hasm
elements, you will have accomplishedm * n
iterations! It has how to "improve" the code, making this complexitym + n
using a dictionary, although this entails an additional memory cost.– Luiz Felipe