skip to Main Content

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


  1. 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.

    const data = [{"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"}];
    
    // Get all `cgi` where tag is `revert`.
    const revertedTags = data.reduce((acc, item) => {
      if(item.tag === 'revert') {
        acc.add(item.cgi);
      }
    
      return acc;
    }, new Set());
    
    // Filter out all elements who are present in `revertedTags` collection.
    const filteredTags = data.filter((item) => !revertedTags.has(item.cgi));
    
    // Result.
    console.log(filteredTags);
    Login or Signup to reply.
  2. An one-liner: you can use a memoized function as a filter to filter the items:

    const data = [{"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"}];
    
    const filteredTags = data.filter((map => e => map[e.cgi] ??= !data.find(e2 => e2.tag === 'revert' && e.cgi === e2.cgi))({}));
    
    console.log(filteredTags);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search