JavaScript Delete an Object from an Array


This code below demonstrates how to delete one object form an array of objects using the splice() method, given the value of one of the object’s properties.

<!DOCTYPE html>
<html>
<body>
<script>
// DELETE an object from an array using splice()
//
// This code demonstrates an array of objects that
// needs to be reduced in size by one object
// by removing an object according to
// one of its property values.
var fruits = [
  { name: "apple", value: 7
  },
  {
    name: "banana", value: 3
  },
  {
    name: "cherry", value: 9
  }
];
// provided by user
var itemName = 'apple';
fruits.forEach(function(item, index){
    console.log(index + ' => '+ item.name + "  " + item.value);
})
function checkObject(item) {
    return item.name === itemName;
}
index = fruits.findIndex(checkObject);
console.log("remove " + itemName + ", index is " + index);
console.log("original fruits length is " + fruits.length);
// if we did not return a negative one value, then go
// ahead and splice it
if (index != -1) {
  fruits.splice(index,1);
}
console.log("new fruits length is " + fruits.length);
fruits.forEach(function(item, index){
    console.log(index + ' => '+ item.name + "  " + item.value);
})
</script>
</body>
</html>

In the console of the Google Chrome browser (press F12) you will see the following output.

jsdeleteobjsplice

At the heart of this code is the splice() method which is described at w3schools.com. The syntax is as follows:

array.splice(index,howmany,item1,…..,itemX)

The index is Required. An integer that specifies at what position to add/remove items, Use negative values to specify the position from the end of the array. howmany is optional. The number of items to be removed. If set to 0, no items will be removed. item1, …, itemX is optional. The new item(s) to be added to the array.

Before using splice() we need to take the string we are looking for and get the index of the array. To do this we use the findIndex() method.

If splice cannot find the object in the array it will return negative one. We therefore need to include an if statement in our code that only splices when we do not get a negative one result.

Leave a comment

Your email address will not be published. Required fields are marked *