0

I have this array of objects and I am wanting to filter out where myDatas.items.flaggedItem is not null and at the same time remove the duplicates where myDatas.items.id are the same. So in this instance I would only expect 2 to be returned

"myDatas":[
  {
    "id": "id1",
    "items":[
       {
         "id": "idOne",
         "flaggedItem": null,
       },
       {
         "id": "idTwo",
         "flaggedItem": 1,
       },
   },
   {
     "id": "id2",
     "items":[
       {
         "id": "idTwo",
         "flaggedItem": 1,
       },
       {
         "id": "idOne",
         "flaggedItem": 2,
       },
   }
]

I have this, but unable to find a good way to remove the duplicates. This accomplishes the first part where I am pulling only items where myDatas.items.flaggedItem is not null, but does not remove the duplicates.

  let test1 = myDatas
    ?.map(myData => {
      let test2 = myData.items?.filter(
        items => items.flaggedItem || items.flaggedItem === 0
      );
      return { ...myData, items: test2 };
    });
2

1 Answer 1

0

Easiest way to filter out the duplicate data is by keeping a duplicates map:

const myData = [
  {
    "id": "id1",
    "items": [
      {
        "id": "idOne",
        "flaggedItem": null,
      },
      {
        "id": "idTwo",
        "flaggedItem": 1,
      },
    ],
  },
  {
    "id": "id2",
    "items": [
      {
        "id": "idTwo",
        "flaggedItem": 1,
      },
      {
        "id": "idOne",
        "flaggedItem": 2,
      },
    ],
  },
];

const duplicates = {};

const dedupedData = myData.map((element) => {
  const items = element.items.filter((item) => {
    if (!item.flaggedItem && item.flaggedItem !== 0) return false;

    if (duplicates[item.id]) return false;
    duplicates[item.id] = true;

    return true;
  });

  return {
    ...element,
    items,
  };
});

console.log(dedupedData);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.