0

I read many answers but I didn't understand how to use splice in this case.. Suppose i have an array named alphabets like - ["a","b","c","d","e"] and i have to remove c from it. I dont want to create another array with c removed instead i want to update the same list each time an item is removed just like remove method in python. I know the index also so it can be like alphabets.remove[3]...to remove c. Please help me i am beginner.

Actually it would be better if there's a way that i can remove using just index number cause the names in array are very tough. Any help is appreciated

1

1 Answer 1

3

To modify the array rather than creating a new one, as you said you'd want the splice method. You pass the index of the item to remove, and the number of items to remove at that index:

const index = theArray.indexOf("c");
theArray.splice(index, 1);

Live Example:

const theArray = ["a","b","c","d","e"];
const rememberArray = theArray; // Just so we can prove it's the same array later
const index = theArray.indexOf("c");
theArray.splice(index, 1);
console.log(theArray);
console.log("Same array? " + (rememberArray === theArray));

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

3 Comments

Can you please help once again.. what if the item inside the array is not a string how can i get its index number ?
@UtkarshTyagi - It doesn't matter what it is, indexOf will find it if you pass the same thing into indexOf, which effectively does a === comparison. Now, if you want to find the index of an object by checking its properties, or a string by a substring, or anything that isn't just a === comparison, you'd use findIndex with a callback (or find to find the object itself).
i have posted a question completely describing my problem It would be really helpful if you would answer there stackoverflow.com/questions/64192200/…

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.