remove trailing elements from array that are equal to zero - better way

后端 未结 2 1846
醉梦人生
醉梦人生 2021-01-18 20:52

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         


        
相关标签:
2条回答
  • 2021-01-18 21:40

    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]
    
    0 讨论(0)
  • 2021-01-18 21:40
    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

    0 讨论(0)
提交回复
热议问题