-1

How can I remove an object from an array?

array = [{id:"1", name:"Jhon"},
         {id:"2", name:"Kabir"},
         {id:"3", name:"Rasel"}];

I want to find the id number and then remove that object. How do i do this?

  • Does this answer your question? [Find object by id in an array of JavaScript objects](https://stackoverflow.com/questions/7364150/find-object-by-id-in-an-array-of-javascript-objects) – Alex Berger Jan 22 '21 at 08:48

1 Answers1

0

array = [{id:"1", name:"Jhon"},
         {id:"2", name:"Kabir"},
         {id:"3", name:"Rasel"}];
         
console.log(remove_by_id( array, '2' ));

function remove_by_id( array, id ) {
  const index = array.findIndex( el => el.id === id );
  if( index !== -1 )
    array.splice( index, 1 )
  
  return array;
}
Rob Monhemius
  • 4,822
  • 2
  • 17
  • 49