remove object in array where id matches x in javascript

To remove an object from an array in JavaScript where the object's ID matches a specific value, you can use the filter() method. Here's an example code snippet:

index.tsx
let arr = [{ id: 1, name: "John" }, { id: 2, name: "Jane" }, { id: 3, name: "Bob" }];

let idToRemove = 2;

arr = arr.filter(obj => obj.id !== idToRemove);

console.log(arr);
// Output: [{ id: 1, name: "John" }, { id: 3, name: "Bob" }]
236 chars
9 lines

In this code, we define an array of objects with id and name properties. We then specify the ID value we want to remove with the idToRemove variable. We then use the filter() method to create a new array that includes all objects except the one where the id property matches idToRemove. Finally, we log the new array to the console to verify that the object with ID 2 has been removed.

Note that the filter() method creates a new array and does not modify the original array. If you want to remove the object from the original array, you would need to assign the output of filter() back to the original array like so: arr = arr.filter(obj => obj.id !== idToRemove);.

gistlibby LogSnag