Explain Codes LogoExplain Codes Logo

Last 5 array elements, but the first one feels left out

javascript
slice
immutability
performance
Anton ShumikhinbyAnton Shumikhin·Dec 4, 2024
TLDR

Snatch the last 5 elements and leave the first behind with two applications of slice():

let likeTheLastGoodCookie = array.slice(1).slice(-5); // Poor first element, always overlooked 😔

First slice(1) politely asks the first element to step aside, while the second slice(-5) takes the trailing five elements, as if they were the last slices of pizza at a lan party.

Too short? I get the hint

If the array size is closer to zero than 6, let's tweak our slicing strategy a bit to avoid a lonely, single-element array.

let doIEvenExist = array.length > 1 ? array.slice(1).slice(-5) : [];

This dipstick check ensures we're not naively trying to slice and dice an almost empty array, reminiscent of trying to divide a single slice of cake amongst a horde of hungry devs.

Size definitely matters

Before throwing the dice with slice(), figure out from which index to start slicing.

let indexWhereSafetyBegins = Math.max(array.length - 5, 1); let safetyFirstLastFive = array.slice(indexWhereSafetyBegins); // Safety scissors cut from the right spot

This particular script ensures we've got the last five elements, excluding Mr. First-in-line, regardless of whether we're dealing with a shopping list or the entire script of War and Peace.

lodash is your cool retriever

If lodash is your buddy, the _.takeRight() function is like having a cool retriever fetch you your Frisbee:

let likeAGoodBoy = _.takeRight(array.slice(1), 5);

Lodash is a good boy, aspiring to fetch you what you need without tripping over its own legs.

Unexpected arrivals and departures

Programming isn't always a ride in park, occasionally we receive guests in the form of unexpected input. Time to keep the spare guest room ready for:

  • Empty arrays: Before you crank up the slicing machine, calm down and check if you've even got a loaf to begin with.
  • Dynamic element retrieval: Why stop at 5? Replace the 5 with a variable, and enjoy all the scalability you need for 'n'-last elements.
  • Performance: Remember, slicing can be like photocopying. It creates duplicates. Making copies of big arrays might get your application groaning like a truck under a heavy load.

Slice it any which way

The slice() is a Swiss Army knife. It doesn't mutate the original array, making it the perfect tool for immutability. A quick stab with it and you've got a nice shallow copy:

let dejaVu = array.slice(); // Duplicating like Agent Smith

However, treat it like a knife: understand its limits and play safe. It's a two-edged blade, taking two arguments, slice(start, end), where start is inclusive and end doesn't know the meaning of the word "included."