Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I filter by id and type in javascript with filter?

I have an array like this:

const arr = [
  {
    id: 1,
    type: 'SOLD'
  },
  {
    id: 1,
    type: 'REVIEWS'
  }
...
];

I want to remove an object in it by id and type. How do I do that?

this code removes all…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

if(type === 'SOLD') {
    return draft.filter((el => el.item.id !== notification_id));
 } else {
   return draft.filter((el => (el.item?.id !== notification_id)));
}

>Solution :

If I understood correctly your question, you cold easily do it with a filter function evaluating both parameters at the same time.
Please have a look at the example below:

const arr = [
  {
    id: 1,
    type: 'SOLD'
  },
  {
    id: 1,
    type: 'REVIEWS'
  },
  {
    id: 2,
    type: 'SOLD'
  },
  {
    id: 2,
    type: 'REVIEWS'
  }
];

const filterData = (array, id, type) => array.filter(e => e.id !== id || e.type !== type)


const filteredArray = filterData(arr, 1, 'SOLD')
console.log(filteredArray)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading