0

I would like to remove one element at index from the list items inside an array of objects using react.

For now, I do not know which method to use.

const [users, setUsers] = useState([
  {
    username: "Peter",
    items: [
      { name: "Bananas 🍌", quantity: 10 },
      { name: "Strawberry 🍓", quantity: 20 },
      { name: "Milk 🥛", quantity: 6 },
    ],
  },
  {
    username: "William",
    items: [
      { name: "Brocolis 🥦", quantity: 3 },
      { name: "Carottes 🥕", quantity: 10 },
      { name: "Honey 🍯", quantity: 2 },
    ],
  },
]);

// Remove element from list item (Pseudo Code)
function removeItem(index: number) {
  const initialState = [...users]
  initialState[userIndex].items.splice(itemIndex, 1)
  setUsers(initialState)
}

Thank you for your help.

5
  • 5
    I don't understand, which element do you want to remove exactly ? Commented Nov 25, 2020 at 11:31
  • I want to remove any item in a user's items list by specifying its index. Commented Nov 25, 2020 at 11:38
  • 1
    @Olivier.C of which user? check my answer too Commented Nov 25, 2020 at 11:38
  • Let's say I want to delete an item from any user's list : items Commented Nov 25, 2020 at 11:52
  • @Olivier.C you should check my answer I think it covers your use case. Commented Nov 25, 2020 at 12:49

2 Answers 2

1

Assuming you want to remove item with index: itemIndex from user with index userIndex user.

function removeItem(userIndex, itemIndex) {
    return users.map((x, i) => {
        if (i === userIndex) return {
            ...x,
            items: x.items.filter((y, j) => j !== itemIndex)
        }
        return x;
    })
}

You have to do it in immutable way since it comes from state.

Sign up to request clarification or add additional context in comments.

Comments

0

You can use Array.prototype.filter for that

function removeItem(index: number) {
  setUsers(users.filter((user, userIndex) => userIndex !== index))
}

You can read more about Array.prototype.filter here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.