skip to Main Content

I have an array of object , I want to remove duplicate one based on ‘documentTypeId’ and ‘flag’ value. Here in below object I want to remove the object having ‘documentTypeId’ value is same and flag value is false. I tried but not getting proper filter. Please find the below code.

const test = [{
    "id": 100,
    "documentTypeId": 3,
    "docName": "test",
    "flag": false
  }, {
    "id": 31184688089,
    "documentTypeId": 1,
    "docName": "test2",
    "flag": true
  },
  {
    "documentTypeId": 3,
    "docName": "test3",
    "flag": true,
    "active": true
  }
]
const res = test.filter((value, index, self) =>
  index === self.findIndex((t) => (
    t.documentTypeId === value.documentTypeId && t.flag == false
  ))
)
console.log(res);

2

Answers


  1. Filter all true values the run it
    Use value.flag instead of hardcoded false

    Hope it works now

    const test = [{
        "id": 100,
        "documentTypeId": 3,
        "docName": "test",
        "flag": false
      }, {
        "id": 31184688089,
        "documentTypeId": 1,
        "docName": "test2",
        "flag": true
      },
      {
        "documentTypeId": 3,
        "docName": "test3",
        "flag": true,
        "active": true
      }
    ]
    const res = test.filter(({flag})=>flag).filter((value, index, self) =>
      index === self.findIndex((t) => (
        t.documentTypeId === value.documentTypeId && t.flag == value.flag
      ))
    )
    console.log(res);
    Login or Signup to reply.
  2. const data = [
      {
        "id": 100,
        "documentTypeId": 3,
        "docName": "test",
        "flag": false
      }, {
        "id": 31184688089,
        "documentTypeId": 1,
        "docName": "test2",
        "flag": true
      },
      {
        "documentTypeId": 3,
        "docName": "test3",
        "flag": false,
        "active": true
      }
    ];
    
    let typeMem = [];
    let filtered = data.filter(({ flag: f, documentTypeId: d }) => 
      f || (typeMem[d] = (typeMem[d] || 0) + 1) && typeMem[d] < 2);
    
    console.log(filtered);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search