Wednesday 12 September 2018

JavaScript: splice: Delete an element from array

Arrays in JavaScript are implemented as objects.

Suppose, if you define array like
var arr = [];
arr[0] = 10;
arr[5] = 21;

Internally it is implemented like associative array like below.
arr = {
         0 : 10
         5 : 21
}

So if you apply delete operator to remove an element from array, it actually don’t remove the element, it sets the value as undefined.

array.html
<!DOCTYPE html>

<html>

<head>
    <title>Array</title>
</head>

<body>
    <script type="text/javascript">
        var arr = [2, 3, 5];

        document.write("arr[0] = " + arr[0] + "<br />");
        delete arr[0];
        document.write("arr[0] = " + arr[0] + "<br />");
    </script>
</body>

</html>

Open above page in browser, you can able to see following data.

arr[0] = 2
arr[0] = undefined

As you see the output, delete don’t deletes the element from array. We should use splice method to delete an element from array.

How to delete an element from array?
Use splice method to actually delete elements from array.

arr.splice(index, count[, elem1, ..., elemN])
Remove count number of elements starting from index and then paste elem1, ..., elemN on their place. elem1...elemN are optional. ‘splice’ function return an array of removed elements.

array.html
<!DOCTYPE html>

<html>

<head>
    <title>Array</title>
</head>

<body>
    <script type="text/javascript">
        function printArray(arr) {
            document.write("<br />Elements in array are<br />");
            for (i = 0; i < arr.length; i++) {
                document.write(arr[i] + " ");
            }
            document.write("<br />");
        }

        var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
        printArray(arr);

        document.write("Removing elements from index 3 to 5 <br />");
        arr.splice(3, 5);
        printArray(arr);

        document.write("<br />Removing elements from index 1 to 2 and add elements a b c d e");
        arr.splice(1, 2, 'a', 'b', 'c', 'd', 'e');
        printArray(arr);
    </script>
</body>

</html>

Open above page in browser, you can able to see following data.

Elements in array are
1 2 3 4 5 6 7 8 9
Removing elements from index 3 to 5

Elements in array are
1 2 3 9

Removing elements from index 1 to 2 and add elements a b c d e
Elements in array are
1 a b c d e 9



Previous                                                 Next                                                 Home

No comments:

Post a Comment