How to remove first array element using the spread syntax

Viewed 6178

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.

4 Answers

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.

Is this what you're looking for?

const input = [1, 0, 2, 3, 4];
const output = [input[0], ...input.slice(2)];

After the question was updated:

const input = [1, 2, 3, 4];
const output = [...input.slice(1)];

But this is silly, because you can just do:

const input = [1, 2, 3, 4];
const output = input.slice(1);

You could use the rest operator (...arrOutput) with the spread operator(...arr).

const arr = [1, 2, 3, 4];
const [itemRemoved, ...arrOutput] = [...arr];
console.log(arrOutput);
Related