Search code examples
javascriptarraysspread-syntax

How to remove first array element using the spread syntax


So I have an array, ex. const arr = [1, 2, 3, 4];. I'd like to use the spread syntax ... to remove the first element.

ie. [1, 2, 3, 4] ==> [2, 3, 4]

Can this be done with the spread syntax?

Edit: Simplified the question for a more general use case.


Solution

  • Sure you can.

    const xs = [1,2,3,4];
    
    const tail = ([x, ...xs]) => xs;
    
    console.log(tail(xs));

    Is that what you're looking for?


    You originally wanted to remove the second element which is simple enough:

    const xs = [1,0,2,3,4];
    
    const remove2nd = ([x, y, ...xs]) => [x, ...xs];
    
    console.log(remove2nd(xs));

    Hope that helps.