Home > Software engineering >  How can I filter by id and type in javascript with filter?
How can I filter by id and type in javascript with filter?

Time:11-23

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

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

CodePudding user response:

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)

  • Related