Getting First and Last Items in Array (and splitting all the rest)

I needed to get the first item from an array lately in JavaScript. Hmmmm … lemme think here. I remember that .pop() is for snagging the last item from the array, like this:

const arr = ["This", "Little", "Piggy"];
const first = arr.pop();
console.log(first);
// "Piggy"

So what’s the opposite of .pop()? (Please pause for light web searching…) Ah ha! It’s .shift()!

const arr = ["This", "Little", "Piggy"];
const first = arr.shift();
console.log(first);
// "This"

(Note that arr[0] is probably the easiest way to get the first item, but play along here. Also it’s kinda nice sometimes if what is cut off from the array remains an array so let’s keep looking…)

But when I reached for this wonderful little helper method, stopped in my tracksNot everyone will run into this issue, because it’s not a problem with arrays in general but with arrays in certain contexts. This is what I saw in the code base I was working on:

image1

The issue is that I was trying to pull this item from an array in which I was not allowed to manipulate. In my case, I was using Apollo GraphQL and the data that I was getting back was in the form of read only property.

Read only? All I’m trying to do here is ask for the first item in an array: I’m not changing anything. OR AM I? (I am.) Turns out both .pop() and .shift() will return those last and first items respectively, but they’ll also manipulate the original array. And my array was un-manipulatable.

What I actually needed was to take an array and get both the first item and all the rest of the items in a new array, while leaving the original array aloneThe .slice() array method had my back here nicely. It won’t mess with the original array.

This will do us nicely:

const arr = ["This", "Little", "Piggy"];
const first = arr.slice(0, 1);
const the_rest = arr.slice(1);
console.log(first); // ["This"]
console.log(the_rest); // ["Little", "Piggy"]

Hey, just what I needed!

Need an easy way to find the correct array method you need? Try Sarah Drasner’s JavaScript Array Explorer:

image2

https://codepen.io/sdras/details/gogVRX

Click here to build your next great project on Media Temple.

Comments

Related Articles