My javascript array
const response = [
{
"userId": "1",
"questionId": "1",
"answeredIndex": 1
},
{
"userId": "1",
"questionId": "2",
"answeredIndex": 0
},
{
"userId": "2",
"questionId": "1",
"answeredIndex": 1
},
{
"userId": "2",
"questionId": "2",
"answeredIndex": 0
},
{
"userId": "3",
"questionId": "1",
"answeredIndex": 0
},
{
"userId": "3",
"questionId": "2",
"answeredIndex": 3
},
{
"userId": "4",
"questionId": "1",
"answeredIndex": 1
},
{
"userId": "4",
"questionId": "2",
"answeredIndex": 0
},
{
"userId": "5",
"questionId": "1",
"answeredIndex": 0
},
{
"userId": "5",
"questionId": "2",
"answeredIndex": 0
}]
I am looking for a solution which will return an array of userIds. Each user has answered two questions(questionId: 1 and questionId: 2). I want the users who have answered both questions same. So, I want to filter my array with an AND condition like below :
if user selected answeredIndex: 1 for questionId: 1 AND if also the same user selected answeredIndex: 0 for questionId: 2 then, I want this user to be pushed in the result array.
I tried below code but it is not working unfortunately.
const targetUsers: string[] = [];
response.forEach((feedback) => {
if ((feedback.questionId === '1' && feedback.answeredIndex === 1) ||
feedback.questionId === '2' && feedback.answeredIndex === 0) {
targetUsers.push(feedback.userId);
}
});
console.log([...new Set(targetUsers)]);
My Expected output should be like below:
[
{
"userId": "1",
"questionId": "1",
"answeredIndex": 1
},
{
"userId": "1",
"questionId": "2",
"answeredIndex": 0
},
{
"userId": "2",
"questionId": "1",
"answeredIndex": 1
},
{
"userId": "2",
"questionId": "2",
"answeredIndex": 0
},
{
"userId": "4",
"questionId": "1",
"answeredIndex": 1
},
{
"userId": "4",
"questionId": "2",
"answeredIndex": 0
}]
So the combination of attribute pairs (questionId, answeredIndex) should be (1,1) AND (2,0) for each user, only then the user will be considered. Will highly appreciate if anyone helps me out here. Thanks in advance.