I am Hack Sparrow
Captain of the Internets.

Truncating an Array in JavaScript

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

var a = ['apple', 'mango', 'rocket', 'moon', 'tiger'];
a.length = 2;
console.log(a);
// ["apple", "mango"]

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

Truncating JavaScript array using the splice method

var a = ['apple', 'mango', 'rocket', 'moon', 'tiger'];
var b = a.splice(2); // Assigning to a variable is not mandatory
console.log(a);
// ["apple", "mango"]

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!

Make a Comment