I have very long array containing numbers. I need to remove trailing zeros from that array.
if my array will look like this:
var arr = [1,2,0,1,0,1,0
Assuming:
var arr = [1,2,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
You can use this shorter code:
while(arr[arr.length-1] === 0){ // While the last element is a 0,
arr.pop(); // Remove that last element
}
Result:
arr == [1,2,0,1,0,1]
var arr = [1,2,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
var copy = arr.slice(0);
var len = Number(copy.reverse().join('')).toString().length;
arr.length = len;
arr -> [1, 2, 0, 1, 0, 1]
how it works
copy.reverse().join('')
becomes "00000000000000000101021"
when you convert a numerical string to number all the preceding zeroes are kicked off
var len = Number(copy.reverse().join('')) becomes 101021
now by just counting the number i know from where i have to remove the trailing zeroes and the fastest way to delete traling elements is by resetting the length of the array.
arr.length = len;
DEMO