I want to filter an object based on the id that I want to remove from the array I am using the filter to remove it but it not working properly my task is I need to remove only that object whose id will match and I will send the remaining data as it is in the payload
const deleteChartData = (id) => {
monitoringResult?.monitoringResults?.opCharts?.filter(
(col) => col.id !== id
);
setMonitoringResult({ ...monitoringResult, monitoringResult });
setTimeout(() => {
formikForm.handleSubmit();
}, 0);
};
3
Answers
you’re not saving filtered results. Filter doesn’t change orignal array, it returns a new array.
Find the index you want to remove, then remove it from a shallow copy and then set that as your new data
Welcome to StackOverflow! In future please try to find already existing posts, because your question could be solved on that way. Here is a guide on how to make a good post on this plattform: How To Ask
However I will help you out now. Your
filter
method doesn’t modify the original array. A new array is returned which includes only elements that pass the filtering you set up. Because of that you have to assign the result of thefilter
method to themonitoringResults
array. Also when the state is updated of thesetMonitoringResult
you should spread the previous state and update themonitoringResults
property properly. In the code it could look like this:My Code: