delete item from array of objects javascript 1

delete item from array of objects javascript

const apps = [
  {id:1, name:'Jon'}, 
  {id:2, name:'Dave'},
  {id:3, name:'Joe'}
]

//remove item with id=2
const itemToBeRemoved = {id:2, name:'Dave'}

apps.splice(apps.findIndex(a => a.id === itemToBeRemoved.id) , 1)

//print result
console.log(apps)
 Run code snippet

Here is what the above code is Doing:
1. We have an array of objects called apps.
2. We have an object called itemToBeRemoved.
3. We use the splice() method to remove the item from the array.
4. We print the result.

The splice() method takes two arguments:
1. The index of the item to be removed.
2. The number of items to be removed.

In our case, we want to remove only one item, so we pass 1 as the second argument.

The first argument is the index of the item to be removed. We use the findIndex() method to find the index of the item to be removed.

The findIndex() method takes a callback function as an argument. The callback function takes one argument, which is the current item in the array.

In our case, we want to find the index of the item with id=2. So, we check if the current item’s id is equal to 2. If it is, we return true.

The findIndex() method returns the index of the first item for which the callback function returns true.

In our case, the index of the item with id=2 is 1. So, the findIndex() method returns 1.

We pass 1 as the first argument to the splice() method. This removes the item with id=2 from the array.

The splice() method returns an array containing the removed items. In our case, the removed item is {id:2, name:’Dave’}.

The splice() method modifies the original array. So, the apps array now contains only two items:

[
{id:1, name:’Jon’},
{id:3, name:’Joe’}
]

Similar Posts