This is a very common use case. I often find myself doing the length - 1 trick:
const myArrayWithLongDescriptiveName = ['red', 'yellow', 'green', 'blue']
const lastItem = myArrayWithLongDescriptiveName[myArrayWithLongDescriptiveName.length - 1]
Proposal
Like Array.pop without mutating the original object
const myArrayWithLongDescriptiveName = ['red', 'yellow', 'green', 'blue']
const lastItem = myArrayWithLongDescriptiveName.getLast() // blue
For symmetry I would also add Array.getFirst equivalent to a non-mutating shift
Thoughs ?
This seem to work for me!:
Object.defineProperty(Array.prototype, "first", {
get() {
return this[0]
},
set(item) {
return this[0] = item
}
})
Object.defineProperty(Array.prototype, "last", {
get() {
return this[this.length -1]
},
set(item) {
return this[this.length -1] = item
}
})
const arr = [1, 2, 3, 4]
arr.first = 100
console.log("first: ", arr.first, ", last: ", arr.last)
// first: 100, last: 4
There was a proposal to introduce yourArray.last (see here), which was later superceded by the more general purpose yourArray.at() proposal.
This let's you do this to get the last item: yourArray.at(-1)
1 Like
And .at(-1)
is available in Firefox from today!
3 Likes
Just checked on Edge. .at
appears to be available here too.
The problem is, the .at
method is not paired with a .setAt
method.
We still need to do array[array.length - 1] = value
or array.pop(); array.push(value)
to set the last item of the array. Only the dropped .lastItem
proposal @theScottyJam mentioned solves the problem.
You can also do arr.splice(-1, 1, v)
, which is from the last item, delete 1 item, and insert v
Yea I missed that, but I donβt think itβs the best solution as something like array[array.length - 1] += value
cannot be done.
@graphemecluster - a +=
operator wouldn't work with a .lastItem()
function either.
@theScottyJam
No, in the proposal you mentioned, .lastItem
is a property with both getter and setter.
1 Like
Oh, whoops, you're right. It's been a while since I looked at it.
1 Like