Get all but the first element in an array using JavaScript?

Answered
suparman21 asked this question 4 months ago
suparman21 on Jan 19

When coding in JavaScript, I have an array that I need to get each element from, but exclude the first one at the 0 index position.

For example, this array:

[1, 4, 21, 41]

Should be converted into this new array:

[4, 21, 41]

Thanks in advance!

4 suggested answers
rusty1_rusty1 on Jan 20

You can use the _.tail() method provided by Lodash:

_.tail(array)
0 replies
yaboy01 on Jan 21

You can use the array.slice(startIndex, endIndex) method:

array.slice(1)

If you leave the endIndex parameter empty, it returns all the elements starting at the index you provided.

0 replies
moon_man41 on Jan 21

shift() is the easiest way to do this:

var array = [1, 4, 21, 41]

array.shift()

// array = [4, 21, 41]
0 replies
nick on Jan 21
var array = [1, 4, 21, 41]

const [, ...newArray] = array

console.log(newArray) // [4, 21, 41]
0 replies
Answered