Today we are going to see how we can Delete data from array using Javascript.
So here we have an array
let players = [ 'Rom', 'Roger', 'Andrew', 'Mark', 'Albert', 'John', 'Steve', 'Jack', 'Manu', 'Jacky', 'Tom' ];
For that we can use javascript function "shift", Here is how we do it
// Removing 1st value from array players.shift();
So output will look something like this
Roger, Andrew, Mark, Albert, John, Steve, Jack, Manu, Jacky, Tom
Now let's see how we can
In this case we use javascript function "pop" like this
// Remove the last value from array players.pop();
Output will have names printed like this
Rom, Roger, Andrew, Mark, Albert, John, Steve, Jack, Manu, Jacky,
Now what if you want to delete some value from array but from the middle somewhere. In this case we use another javascript function "splice". Here is how
Let's say we need to remove value "John" in given array, For that we need to check where "John" value present in array(At what index). We can find location of value in array using javascript function "indexOf". Here is How
players.indexOf('John'); // It will return 5 as John is in array at 5th value(Note: array index start from 0). So // name "Rom" is at index 0 and "Roger" is at index 1
Now we use "splice method"
Here
// Remove specific value from array players.splice(players.indexOf('John'), 1);
1st argument is (Index from where you want to remove data)
2nd Argument is How many values to remove
So in our example we are using index of "John" and passing "1" as second argument. So it removes only one value from array which is "John" in this case.
Output will be like this
Rom, Roger, Andrew, Mark, Albert, Steve, Jack, Manu, Jacky, Tom,
Note: Data returns does not have "John" in it.
Hope this helps