Monday, 3 September 2018

JavaScript: trim elements of array

You can trim the elements of array by calling the pop method on the array. There is another smart way also; using length property of array you can trim the array.

arr.length = 3;
Above statement keeps only 3 elements.

array.html
<!DOCTYPE html>

<html>

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

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

        var arr1 = [2, 3, 5, 7, 11, 13, 17, 19, 23];
        printArr(arr1);

        document.write("<br /><br /> Trimming last 3 elements");
        arr1.length = arr1.length - 3;
        printArr(arr1);

        document.write("<br /><br /> Trimming last 4 elements");
        arr1.length = arr1.length - 4;
        printArr(arr1);
    </script>
</body>

</html>

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

Elements in array are
2 3 5 7 11 13 17 19 23

Trimming last 3 elements
Elements in array are
2 3 5 7 11 13

Trimming last 4 elements
Elements in array are
2 3


Previous                                                 Next                                                 Home

No comments:

Post a Comment