In JavaScript you can use an array which is used to store a set of values in a variable. You can add or remove values in an array at any index position.
Below we will discuss a variety of methods that are used to add or remove an element from an array. Let's go through it :
pop() function: pop() method remove elements from the end of an array.
shift() function: shift() method is used to remove elements from the beginning of an array.
splice() function: splice() method is used to remove elements from a specific index of an array.
filter() function: filter() method is used to remove elements programmatically.
Let's check all the method one by one in the below example :
<!DOCTYPE html>
<html>
<head>
</head>
<body>
</body>
<script>
function func() {
var arr = ['shift', 'splice', 'filter', 'pop'];
var popped = arr.pop();
document.write('Removed element: ' + popped + '<br>');
document.write('Remaining elements: ' + arr + '<br>' + '<br>');
}
func();
var array = ['pop', 'splice', 'filter', 'shift']
document.write('Original array: ' + array + '<br>')
while (array.length) {
array.pop();
}
document.write('Array Length: ' + array.length + '<br>' + '<br>');
function shifted() {
var arr = ['shift', 'splice', 'filter', 'pop'];
var shifted = arr.shift();
document.write('Removed element: ' + shifted + '<br>');
document.write('Remaining elements: ' + arr + '<br>' + '<br>');
}
shifted();
function spliced() {
var arr = ['shift', 'splice', 'filter', 'pop'];
// Removing the specified element from the array
var spliced = arr.splice(1, 1);
document.write('Removed element: ' + spliced + '<br>');
document.write('Remaining elements: ' + arr + '<br>' + '<br>');
}
spliced();
</script>
</html>
Hope this code will be helpful for you.
Happy Coding!
Join MindStick Community
You need to log in or register to vote on answers or questions.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
In JavaScript you can use an array which is used to store a set of values in a variable. You can add or remove values in an array at any index position.
Below we will discuss a variety of methods that are used to add or remove an element from an array. Let's go through it :
Let's check all the method one by one in the below example :
Hope this code will be helpful for you.
Happy Coding!