Get all but the last element in an array?

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

If I have a JavaScript array like this:

[1, 2, 3, 4, 5, 6]

How can I return all the elements in that array besides the last one?

I'm coding in JavaScript.

3 suggested answers
suparman21 on Jan 20

Lodash has a _.initial() method you can use:

const array = [1, 2, 3, 4, 5, 6]

_.initial(array) // [1, 2, 3, 4, 5]

This gets all but the last element of an array.

0 replies
moon_man41 on Jan 20 · Edited

This can be done easily with the slice() method:

array.slice(0, array.length - 1)

// converts [1, 2, 3, 4, 5, 6] => [1, 2, 3, 4, 5]
0 replies
yaboy01 on Jan 20

Here's a function you can use to get all elements in an array besides the last:

function getInitial(array) {
  let length = array == null ? 0 : array.length
  return length ? array.slice(0, length - 1) : 0
}

Use the function like this:

const array = [1, 2, 3, 4, 5, 6]

getInitial(array) // [1, 2, 3, 4, 5]
0 replies
Answered