0

Hi folks I have the following array

const options = [
    'option one', 
    'option two', 
    'some other random string', 
    'another random string', 
    'option last one', 
]

If I want to remove something from the middle of this array which also update the indexes, I tried delete arr[ind] but that does not update the index. Want to completely remove from that array.

Regards

2 Answers 2

1

You can try to filter it out by index.

options.filter((item, index) => index !== 3);

Or by name:

options.filter((item) => item !== 'option one');
Sign up to request clarification or add additional context in comments.

3 Comments

It works for me in my terminal. How is it not working?
You need to reassign the above-mentioned expressions to a new variable and it will contain the old data minus the condition.
If for some reason, you have to keep the same array reference. you can simply use the splice method: options.splice(ind, 1)
1

you can use splice as

options.splice(index,1)

if you want to use the filter method you should store the result because filter method does not mutate the array on which it is called, but returns a new array.

2 Comments

Thank you @Hashem Taha, this is even better I would have accepted your answer but I have already accepted Joshua Obritsch answer.. thank you
Actually, I thought that because this thread was tagged with reactjs, it would be better not to mutate the array, as that wouldn't trigger a re-render. This is of course assuming the array is stored in state.

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.