Reputation: 1
I can't figure out how to complete this function. I have filtered through to find the variable that matches the id but now I need to match that item to the delItem var and delete it.
function deleteToDo(tot) {
let delItem = toDos.filter((remove) => remove.id === tot);
/// i need to remove item from toDos array that matches delItem.
renderTheUI(toDos);
}
Upvotes: 0
Views: 33
Reputation: 191976
Array#filter returns an array, with all items that match the predicate. Instead of getting the item that you want to remove, get an array without the item by checking that the id
is not equal to tot
. Then use the filtered array in renderTheUI
:
function deleteToDo(tot) {
const filteredToDos = toDos.filter((item) => item.id !== tot);
renderTheUI(filteredToDos);
}
I would suggest moving the call to renderTheUI
out of the deleteToDo
method, since it might be very confusing. The deleteToDo
will return an updated array, and then you can render the new array:
function deleteToDo(tot) {
return toDos.filter((item) => item.id !== tot);
}
const filteredToDos = deleteToDo(2);
renderTheUI(filteredToDos);
Upvotes: 1
Reputation: 196002
You do not need to find the element with filter
but its index in the array.
function deleteToDo(tot) {
let delIndex = toDos.findIndex((remove) => remove.id === tot);
if (delIndex !== -1){ // if element was found
toDos.splice(delIndex,1); // remove the element from the toDos array
}
renderTheUI(toDos);
}
Upvotes: 0