I have a json object with key cgi, tag and name
key where cgi is repeated in any multiple object if any cgi get the tag as ‘revert’ then that cgi should not get returned.
[
{
"cgi": "abc-123",
"tag": "revert",
"name": "Piyush"
},
{
"cgi": "abc-123",
"tag": null,
"name": "Piyush"
},
{
"cgi": "abc-456",
"tag": null,
"name": "Piyush"
},
{
"cgi": "abc-789",
"tag": null,
"name": "Piyush"
}
]
Then the output will be
[
{
"cgi": "abc-456",
"tag": null,
"name": "Piyush"
},
{
"cgi": "abc-789",
"tag": null,
"name": "Piyush"
}
]
Attempt:
data = data.filter(es => es.tag == 'filter')
abc-123
got rejected as in first index tag is ‘revert’. I have tried using filter but it doest gave me appropriate answer.
2
Answers
You can use reduce() to create a collection of all reverted
cgi
values. Afterwards you can use filter() out all unwanted values based in this collection.*Instead of Set you could also simply use an array. I’ve used a Set so we don’t get duplicate values.
An one-liner: you can use a memoized function as a filter to filter the items: