Explain Codes LogoExplain Codes Logo

Getting the last element of a split string array

javascript
string-manipulation
array-methods
javascript-utility-functions
Anton ShumikhinbyAnton Shumikhin·Sep 21, 2024
TLDR

Want the last element of an array derived from a split string? Here's fast food for your code using split() and pop():

let last = "a,b,c".split(",").pop(); // "c" pops up like a toast!

No need to loop. pop() simply serves the last item post-split. Handling different separators, such as spaces? Try this recipe with a regular expression:

let last = "a, b c".split(/[, ]+/).pop(); // voilà! It's "c"

This technique doesn't let trailing separators rob the toast of your bread! 🍞

Nitty-gritty methods

When your string enjoys costume parties

What happens when your delimiters come in a cocktail of forms? You can still split with multiple separators like commas or spaces using:

let fancyString = "one, two three".split(/[, ]+/).pop(); // "three" amidst the merriment

Now the party (/[, ]+/) doesn't stop at commas and spaces!

Safe wisdom in a crowd

If your crowd (the string) may not have any separators at all, this function won't leave you alone:

function lonelyAtTheParty(str) { let parts = str.split(/[, ]+/); return parts.length > 1 ? parts.pop() : str; // Never walk alone with just one word or no separators }

Trimming that stylish beard

Whitespace can sometimes be your string's beard. Time to give it a trim before splitting:

let cleanedString = " a, b, c ".trim().split(/[, ]+/).pop(); // Now "c" can flaunt its clean shave!

Road less travelled

Look Ma, no modifications!

You wish to preserve the array while accessing the last element because, who likes spoilers?

let preserved = arr.slice(-1)[0]; // Copycat method! Shows the last element without a hint of spoilers

Overturned cart- not on this road

You might see reverse()[0] for getting the last element, but best to dump it in the bin 🗑️ because it:

  • Upends the original array like an overturned cart.
  • Is a lousy performer in front of large crowds (arrays).

Checking under the hood

While testing your function with various strings, console.log() is your friendly mechanic:

console.log(getTheToast("test1, test2, test3")); // "test3" is the toast of the town!

Use alert(thingToAlert) to flash alerts to the user in a UI context.