Remove Item in an Array in JavaScript

How can I remove a specific item from an array in javascript?

Last updated:7/20/2021 1:38:25 AM

1 Answers

Ethan Karla
Ethan Karla

A JavaScript array is a single variable used to store a set of elements or values. You can add or remove elements from the array at any position. In this article, we will discuss the different ways to remove elements from an array.

There are many methods that is used to remove elements from JavaScript array which are discussed below:

  • pop() function: This method is used to remove elements from the end of an array.
  • shift() function: This method is used to remove elements from the beginning of an array.
  • splice() function: This method is used to remove elements from a specific index of an array.
  • filter() function: This 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!

Answer