Reputation: 1489
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
Upvotes: 0
Views: 63
Reputation: 1074666
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));
Upvotes: 3