0

I have an array like this

var items = [{id:'1',token:'jj'},{id:'2',token:'kk'}];

I would like to delete an object from the array that matches id = 2

Here is my solution

//find the corresponding object
let obj=items.find((item) => item.id=='2');
//loop through the original and delete

Is there any other way to do this more efficiently??

zoran404
  • 1,682
  • 2
  • 20
  • 37
shamon shamsudeen
  • 5,466
  • 17
  • 64
  • 129

4 Answers4

0

Use Array#filter function for deleting item/s from the array. It actually returns a new array containing those items which corresponds to the predicate.

let items = [{id:'1',token:'jj'},{id:'2',token:'kk'}];
let filtered = items.filter(item => item.id !== '2');

console.log(filtered);

For removing from the original array

let items = [{id:'1',token:'jj'},{id:'2',token:'kk'}];
let index = items.findIndex(item => item.id === '2');

items.splice(index, 1);

console.log(items);
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
0

I would like to suggest using splice, this doesn't change the reference of the existing array but just removes the desired element..

let items = [{id:'1',token:'jj'},{id:'2',token:'kk'}];

let indexToRemove = items.findIndex((eachElem) => {return eachElem.id == 2})
items.splice(indexToRemove, 1)
console.log(items)
Ashish Ranjan
  • 12,760
  • 5
  • 27
  • 51
0

You can check the console :D

var items = [{id:'1',token:'jj'},{id:'2',token:'kk'}, {id:'4',token:'kk'}, {id:'2',token:'kl'}];
items.forEach(item =>{
 if(item['id'] == '2') items.splice(items.indexOf(item),1)
})

console.log(items)
Akhil Aravind
  • 5,741
  • 16
  • 35
0

You can use splice() with forEach() too:

var items = [{id:'1',token:'jj'},{id:'2',token:'kk'}];
items.forEach((item, index) => {
   if(item.id === '2'){
     items.splice(index,1);
   }
});
console.log(items);
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62