Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

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





Array



"text/javascript">
function printArr(arr) {
document.write("
Elements in array are
"
);
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("

Trimming last 3 elements"
);
arr1.length = arr1.length - 3;
printArr(arr1);

document.write("

Trimming last 4 elements"
);
arr1.length = arr1.length - 4;
printArr(arr1);





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


This post first appeared on Java Tutorial : Blog To Learn Java Programming, please read the originial post: here

Share the post

JavaScript: trim elements of array

×

Subscribe to Java Tutorial : Blog To Learn Java Programming

Get updates delivered right to your inbox!

Thank you for your subscription

×