Skip to content
Advertisement

How can I remove a specific index from an array and then insert a new one on that same index?

I am trying to do one thing but I have 2 choices

  1. Remove a specific item/index from an array and then insert a new one in that same index.
  2. Do not remove the item but edit it with new data.

I have this piece of code:

const handleClick = () => {
    for (let i = 0; i < qs.length; i++) {
      if (qs[i].id === getNewQ.id) {
        const qsCopy = [...qs].filter((q) => q.id !== getNewQ.id);

        return [...qsCopy, { ...newGroup }];
      }
    }

    return [...qs];
  };

It removes the item from the array, but when it adds the new item, it adds it to the last index. But what I need, is this new item to be added to the index where the other item was removed.

Is it clear?

I created a reproducible example: https://codesandbox.io/s/pedantic-darwin-4tty0?file=/src/App.tsx:912-1171

In the sample, you will notice how the new item gets added to the last index. It needs to be as generic as possible because it is dynamic. Not all the time would be the same index.

Advertisement

Answer

Map the qs instead, and when the ID matches, return the newGroup instead of the previous item in state:

const handleClick = () => qs.map((q) => (
  q.id === getNewQ.id
    ? { ...newGroup }
    : q
));
Advertisement