How do you truncate an array in JavaScript?#

There are two ways of truncating an array in JavaScript. One takes advantage of the fact that the length property of the Array object is writable, another uses the splice method of the Array object.

Truncating JavaScript array using the length property:

Run
Clear

In the above code the array is truncated to two items, and only 'apple' and 'mango' are left.

Truncating JavaScript array using the splice() method:

Run
Clear

In the above code too the array is truncated to two items. Splice will also return the items that were truncated from the array.

Choose which ever way fits your need. If you just need to truncate the array, you could go with the length method, if you need to get the items that were truncated you should use the splice() method.

Happy array truncating!

Tweet this | Share on LinkedIn |