javascript - remove trailing elements from array that are equal to zero - better way -
i have long array containing numbers. need remove trailing zeros array.
if array this:
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];
i want remove except [1, 2, 0, 1, 0, 1]
.
i have created function doing expected, i'm wondering if there build in function use.
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]; for(i=arr.length-1;i>=0;i--) { if(arr[i]==0) { arr.pop(); } else { break; } } console.log(arr);
can done better/faster?
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 shorter code:
while(arr[arr.length-1] === 0){ // while last element 0, arr.pop(); // remove last element }
result:
arr == [1,2,0,1,0,1]
Comments
Post a Comment