Answered
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.
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.
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]
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]