Utkarsh Tyagi
Utkarsh Tyagi

Reputation: 1489

How to remove an element from array in javascript without making a new?

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

Answers (1)

T.J. Crowder
T.J. Crowder

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

Related Questions