Home > Back-end >  How to remove item form array?
How to remove item form array?

Time:07-18

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!

CodePudding user response:

Assuming that you want to change the first object and you want do dynamically filter the answers based on your itemId, the onDelete function would look like this:

  const onDelete = useCallback((itemId) => {
    setItems((prev) => [
      { answers: prev[0].answers.filter(({ id }) => id !== itemId) },
      ...prev.slice(1),
    ]);
  }, []);

CodePudding user response:

I've expanded @sm3sher 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);
},[]);

CodePudding user response:

You should create a new object, whose answers property is the filtered original. The filter callback can be ({id}) => id != 2:

   newItems[0] = { answers: newItems[0].answers.filter(({id}) => id != 2) };

CodePudding user response:

newItems = newItems.map(item => { return item.answers.filter(answer => answer.id !== 2)})
  • Related