Delete an element from an array in JavaScript and React js using ID
Here is an example of how you can delete an element from an array in JavaScript using its id
property:
const array = [{id: 1, name: 'John'}, {id: 2, name: 'Jane'}, {id: 3, name: 'Jack'}];
function deleteById(array, id) {
for (let i = 0; i < array.length; i++) {
if (array[i].id === id) {
array.splice(i, 1);
break;
}
}
}
deleteById(array, 2);
// array is now [{id: 1, name: 'John'}, {id: 3, name: 'Jack'}]
This function takes an array and an id
as arguments, and then iterates over the array looking for an object with a matching id
property. When it finds a match, it removes the object from the array using the splice()
method.
Here is an example of how you can use the above function in a React or Next.js component to delete an element from an array:
import React, { useState } from 'react';
function MyComponent() {
const [array, setArray] = useState([{id: 1, name: 'John'}, {id: 2, name: 'Jane'}, {id: 3, name: 'Jack'}]);
function deleteById(id) {
for (let i = 0; i < array.length; i++) {
if (array[i].id === id) {
array.splice(i, 1);
break;
}
}
setArray([...array]);
}
return (
<div>
{array.map(item => (
<div key={item.id}>
<span>{item.name}</span>
<button onClick={() => deleteById(item.id)}>Delete</button>
</div>
))}
</div>
);
}
This component renders a list of objects in the array
state variable, and displays each object's name
property in a span
element. It also includes a Delete
button for each object, which when clicked will call the deleteById()
function and pass in the object's id
as an argument. The deleteById()
the function then removes the object from the array
using the splice()
method, and updates the state using the setArray()
function.