Home > Software engineering >  Problem with deleting array which containts other arrays with specific id item in React
Problem with deleting array which containts other arrays with specific id item in React

Time:04-27

I have Array which containts a lots of arrays which containts {id and content}.

Example : [Array(1), Array(1), Array(1)].

Im trying to delete Array with ID param. It deletes but state of Array.Length doesnt change because i only deleted Item of array ,not whole of one array.

What i want to do is delete () -> than result should be

[[Array(1), Array(1)]

What i got? [Array(0), Array(1), Array(1)]

There is code what im tried to do :

return (
   <div>
      <h1>{tasks.length}</h1>
         {tasks.map((task) => {
            return (<div>
               {task.map((con) => {
                  return (<div>
                     <h3 className="hrandom">{con.content}
                     <button type="button"  onClick={() => { deleted(con.id) }}>Delete</button></h3>
                  </div>
               )
            })}
         </div>)
      })
   }
</div>)

And the delete function :

const deleted = (id) => {
   Axios.delete('http://localhost:3001/api/delete/', { data: { id: id } }).then((res) => {
      console.log(res.data)
   });
   const b = tasks.map((tod) => tod.filter((i) => i.id !== id ));
   setTasks(b);
};

CodePudding user response:

In your map, you're removing the items from the inner array but not the outer array itself. You could do this in a single line, but for simplicity and readability, add a second filter to the outer array:

const b = tasks.map((tod) => tod.filter((i) => i.id !== id )).filter(arr => arr.length > 0);

This will remove any inner arrays that have been emptied, in a very readable manner. However, noting the inner array always has length 1, you could destructure cleanly like so:

const b = tasks.filter(([{ id: inner }]) => inner !== id);

The destructure syntax takes the id property of the object that is the first element of the inner array, and compares it to id.

CodePudding user response:

For your example; instead of using a filter inside a map function - which still returns an array of the same length, you should use the filter function to filter out the parent array directly:

const b = tasks.filter((tod) => tod.findIndex((i) => i.id === id ) < 0);

However, if there is only one array entry that will contain that id, filter may not be the greatest choice as it will loop across the entire tasks array even if the id has already been found. In such case, I would recommend first finding the index of the element that contains an array with the id and using array.splice to remove it from the tasks array as follows:

const index = tasks.findIndex((tod) => tod.findIndex((i) => i.id === id ) > -1);
if (index > 0) {
  tasks.splice(index, 1);
}
  • Related