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

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -