How to Remove Objects from Arrays by ID in JavaScript
In JavaScript, there are various ways to remove an object from an array based on its ID. This can be useful when working with arrays of objects and needing to delete a specific object by its unique identifier. So in this blog post, we will explore two common methods to achieve this.
Removing an Object by ID Using the filter() Method
<script> const myArray = [ { id: 1, name: 'Red' }, { id: 2, name: 'Green' }, { id: 3, name: 'Blue' }, { id: 4, name: 'Black' } ]; const idToRemove = 2; const updatedArray = myArray.filter(obj => obj.id !== idToRemove); console.log(updatedArray); </script>
Explanation:
- The code starts by defining an array myArray that contains objects with an id and a name property.
- The idToRemove variable is set to the ID of the object that we want to remove from the array.
- The filter() method is used to create a new array updatedArray that contains all the objects from myArray except the one with the id that matches idToRemove variable's value.
- The filter() method takes a callback function that is called for each object in the array. The callback function returns true if the object should be included in the new array, and false if it should be excluded.
- Then the updated array updatedArray is logged to the console using the console.log() .
How to Remove an Object by ID Using the splice() Method
<script> const myArray = [ { id: 1, name: 'Red' }, { id: 2, name: 'Green' }, { id: 3, name: 'Blue' }, { id: 4, name: 'Black' } ]; const idToRemove = 2; const indexToRemove = myArray.findIndex(obj => obj.id === idToRemove); if(indexToRemove !== -1) { myArray.splice(indexToRemove, 1); } console.log(myArray); </script>
Explain:
- The code starts by defining an array myArray that contains objects with an id and a name property.
- The idToRemove variable is set to the ID of the object that we want to remove from the array.
- The findIndex() method is used to find the index of the object in the array that has the id that matches idToRemove. The index is stored in the indexToRemove variable.
- If the indexToRemove variable is not equal to -1 (which means that an object with the specified id was found), the splice() method is used to remove the object from the myArray array. The splice() method takes two arguments: the index of the object to remove, and the number of objects to remove (in our case, just 1).
save
listen
AI Answer
How to Remove Objects from Arrays by ID in JavaScript
1
In JavaScript, there are various ways to remove an object from an array based on its ID. …
asked
Apu
1 answers
2915
In JavaScript, there are various ways to remove an object from an array based on its ID. …
Answer Link
answered
Apu
<script>
let array = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' },
{ id: 3, name: 'Charlie' }
];
let idToRemove = 2;
let filteredArray = array.filter(item => item.id !== idToRemove);
console.log(filteredArray);
</script>