I have a bunch array of objects with participants and messages, I want to filter the object with the below array of two participants, can anyone help with this
this is the example participnats of array :
["61badffe4ccf060b329441e0","61bc33a84ccf060b32944354"]
bunch of sample messages and participants :
JavaScript
x
48
48
1
{
2
"messages": [],
3
"participants": [
4
"61badffe4ccf060b329441e0",
5
"61bae01b4ccf060b329441ef"
6
],
7
"_id": "61bae0394ccf060b329441fb",
8
},
9
{
10
"messages": [],
11
"participants": [
12
"61bae1014ccf060b3294420e",
13
"61bae01b4ccf060b329441ef"
14
],
15
"_id": "61bb230c4ccf060b3294421c"
16
},
17
{
18
"messages": [],
19
"participants": [
20
"61badffe4ccf060b329441e0",
21
"61bc33a84ccf060b32944354"
22
],
23
"_id": "61d476dff651471663a72971",
24
},
25
{
26
"messages": [],
27
"participants": [
28
"61badffe4ccf060b329441e0",
29
"61e54b82eab592e7fef65656"
30
],
31
"_id": "61e54ba3eab592e7fef6567a",
32
]
33
34
35
36
37
38
**expected below object after filter participants:**
39
40
```{
41
"messages": [],
42
"participants": [
43
"61badffe4ccf060b329441e0",
44
"61bc33a84ccf060b32944354"
45
],
46
"_id": "61d476dff651471663a72971",
47
},
48
Advertisement
Answer
You might wanna use Array.filter()
and also in your case you should check every element from that array which should match your criteria.
JavaScript
1
38
38
1
const input = [{
2
"messages": [],
3
"participants": [
4
"61badffe4ccf060b329441e0",
5
"61bae01b4ccf060b329441ef"
6
],
7
"_id": "61bae0394ccf060b329441fb",
8
},
9
{
10
"messages": [],
11
"participants": [
12
"61bae1014ccf060b3294420e",
13
"61bae01b4ccf060b329441ef"
14
],
15
"_id": "61bb230c4ccf060b3294421c"
16
},
17
{
18
"messages": [],
19
"participants": [
20
"61badffe4ccf060b329441e0",
21
"61bc33a84ccf060b32944354"
22
],
23
"_id": "61d476dff651471663a72971",
24
},
25
{
26
"messages": [],
27
"participants": [
28
"61badffe4ccf060b329441e0",
29
"61e54b82eab592e7fef65656"
30
],
31
"_id": "61e54ba3eab592e7fef6567a",
32
}
33
];
34
35
const filterByParticipants = ["61badffe4ccf060b329441e0","61bc33a84ccf060b32944354"];
36
const output = input.filter(el => el.participants.every(el => filterByParticipants.includes(el)));
37
38
console.log(output);