
· typescript · 2 min read
Get all but last element in TypeScript
A small article about removing last element in TypeScript, mostly a matter of read-ability
What if you want to get all elements but the last one inside an array in TypeScript ?
Well, it’s a JS feature, that should be relevant in any environment.
Naïve answer
The answer is
// remove only the last element of array a
let b = a.slice(0, -1);
// a is left as-is
// b is all but the last element
A more complete TS example would be
const a: number[] = [1, 2, 3, 4];
const result = a.slice(0, -1);
console.log(result); // Will output [1, 2, 3]
console.log(a); // Will output [1, 2, 3, 4]
However, I’m not 100% satisfied with that.
It works, and has no side-effect, which means you can confidently pipe the output.
But it’s not very readable.
Code for others
There is no a.getAllButLastElement
, which would be a lot more convenient to read (and to remember!)
So if you want to avoid over-engineering, you have no other option than commenting directly the code :
const a: number[] = [1, 2, 3, 4];
const result = a.slice(0, -1); // remove last elt only
console.log(result);
console.log(a);
Mmh works, it is readable, but I’m still not 100% satisfied with that.
It’s not re-usable accross the project
Reusable all but last in TypeScript
So finally I would use something like this :
function allButLast<T>(arr: T[]): T[] {
return arr.slice(0, -1);
}
const a: number[] = [1, 2, 3, 4];
const result = allButLast(a);
console.log(result);
console.log(a);
Good!
Now this is reusable, and self-documented.
Summary
So that’s it for today, solve this was not a big deal, but you can notice how to tackle elegantly a simple problem on real-world projects.
Best,
David