How to remove element in array object in javascript

To remove an element from an array in JavaScript, you can use the splice() method. The splice() method changes the content of an array by removing or replacing elements.

Here’s an example of how to remove an object from an array of objects based on its index:

let arr = [
  {id: 1, name: "John"},
  {id: 2, name: "Jane"},
  {id: 3, name: "Mike"}
];
let index = 1; // index of the object to be removed
arr.splice(index, 1); // remove one object at the specified index
console.log(arr); // Output: [{id: 1, name: "John"}, {id: 3, name: "Mike"}]

In the above example, we define an array of objects arr with three objects. We then define a variable index that represents the index of the object to be removed, which in this case is 1. Finally, we call the splice() method on the array arr, passing in the index and the number of objects to be removed (in this case, just one).

You can also remove objects based on their property values, using the findIndex() method to get the index of the object to be removed:

let arr = [
  {id: 1, name: "John"},
  {id: 2, name: "Jane"},
  {id: 3, name: "Mike"}
];
let value = "Jane"; // value of the property to be matched
let index = arr.findIndex(obj => obj.name === value); // get the index of the object to be removed
if (index !== -1) { // check if the object exists in the array
  arr.splice(index, 1); // remove one object at the specified index
}
console.log(arr); // Output: [{id: 1, name: "John"}, {id: 3, name: "Mike"}]

In this example, we define an array of objects arr with three objects. We then define a variable value that represents the value of the property to be matched, which in this case is “Jane”. We use the findIndex() method to get the index of the object to be removed based on the value of the name property, and then we check if the object exists in the array (by checking if the findIndex() method returns a value other than -1). If the object exists, we call the splice() method on the array arr, passing in the index and the number of objects to be removed (in this case, just one).