DEV Community

David Boureau
David Boureau

Posted on • Originally published at alsohelp.com

Get all but last element in TypeScript

I wrote this content originally on my website : https://alsohelp.com/blog/typescript-get-all-but-last-element

Whereas the answer is initially pretty straightforward, this blog article is mostly for beginners, and how to think about code readability for others.

Here is the article :


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
Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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

Top comments (2)

Collapse
 
banderyk profile image
Yurii Oliiarnyk

Redundate function
slice is already reusable and self-documenting

with this approach we will have to create dozens of extra functions like:
allButLast
allButFirst
allButLastAndFirst
allButTwoFirst
allButTwoLast

Collapse
 
bdavidxyz profile image
David Boureau

@banderyk thanks for your comment. I disagree here, slice is not self documenting. Inly if you can remember how it works. I prefer the list of extra function you gave. Matter of preference though :) Best