javascriptarrays

Remove n-th elements from the end of an array


I have an array like this:

array = [1,2,3,4,5,6,7,8]

and I want to remove for example the 4 last values so as my array becomes this:

array = [1,2,3,4]

I used array.splice(array.length - 4, 1) but it didn't work. Any ideas?


Solution

  • You can use the function slice as follow:

    .slice(0, -4)
    

    This approach doesn't modify the original Array

    //                                    +---- From 0 to the index = (length - 1) - 4,
    //                                    |     in this case index 3.
    //                                  vvvvv
    var array = [1,2,3,4,5,6,7,8].slice(0, -4);
    console.log(array);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    This approach modifies the original Array

    var originalArr = [1, 2, 3, 4, 5, 6, 7, 8];
    
    //                     +---- Is optional, for your case will remove 
    //                     |     the elements ahead from index 4.
    //                     v
    originalArr.splice(-4, 4);
    console.log(originalArr);
    
    //----------------------------------------------------------------------
    
    originalArr = [1, 2, 3, 4, 5, 6, 7, 8];
    //                  +---- Omitting the second param.
    //                  |     
    //                  v
    originalArr.splice(-4);
    console.log(originalArr);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    Docs