javascriptreact-native

How to remove item form array?


I have the following array in my React naitve app.

  const [items, setItems] = useState([
    { answers: [{ id: 1 }, { id: 2 }] },
    { answers: [{ id: 1 }] },
    { answers: [{ id: 1 },] },
  ]);

I want to delete item from first row with id 2 So the final should look like that

[
    { answers: [{ id: 1 }] },
    { answers: [{ id: 1 }] },
    { answers: [{ id: 1 }] },
  ]

How can i do that ? I tried to start like this

  const onDelete = useCallback((itemId) => {
    var newItems = [...items];

    newItems = newItems[0].answers.filter(....) //I don't know how to continue

    setItems(newItems);
  }, []);

Sorry for the question but I'm new to react-native and javascript!


Solution

  • I've expanded @rjumatov answer to allow removing answer ids at any index.

    const onDelete = useCallback((answerId=2,itemIndex=0)=>{
      const newItems = [...items];
      let currentItem = newItems[itemIndex]
      currentItem.answers = currentItem.answers.filter(({id})=> id !== answerId)
      newItems[itemIndex] = currentItem;
      setItems(newItems);
    },[]);