Remove an object item from array by ID in Javascript

Remove an object item from array by ID in Javascript

Example: We have an array like this:

const listItems = [
  {
    id: 1,
    name: 'a'
  },
  {
    id: 2,
    name: 'b'
  },
  {
    id: 3,
    name: 'c'
  }
];


I want to remove the item has id: 2

To do that we will use filter method like this:

const filterId = 2;

const newListItems = listItems.filter(obj => {
  return obj.id !== filterId;
})

// or 

const newListItems = listItems.filter(obj => obj.id !== filterId)

console.log(newListItems);
// result will be:

// [
//   {
//     id: 1,
//     name: 'a'
//   },
//   {
//     id: 3,
//     name: 'c'
//   }
// ];


The filter() method creates a new array with all elements that pass the test implemented by the provided function.


© 2019 4codev

Created with love by Sil.