Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 905
coops22 Avatar asked Aug 25 '18 22:08

coops22


3 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.

like image 192
Aadit M Shah Avatar answered Oct 22 '22 04:10

Aadit M Shah


Destructuring assignment

var a = [1, 2, 3, 4];

[, ...a] = a

console.log( a )
like image 11
Slai Avatar answered Oct 22 '22 03:10

Slai


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);
like image 3
Evert Avatar answered Oct 22 '22 04:10

Evert