Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

100
Views
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!

about 4 years ago · Santiago Gelvez
3 answers
Answer question

0

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),
    ]);
  }, []);
about 4 years ago · Santiago Gelvez Report

0

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);
},[]);
about 4 years ago · Santiago Gelvez Report

0

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) };
about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!