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 <span class="c5">.pop()</span> is for snagging the last item from the array, like this:

<span class="c3">const arr = ["This", "Little", "Piggy"];
</span><span class="c3">const first = arr.pop();
</span><span class="c3">console.log(first);
</span><span class="c3">// "Piggy"</span>

So what’s the opposite of .pop()? (Please pause for light web searching…) Ah ha! It’s <span class="c5">.shift()</span>!

<

p class=”c1″><span class="c3">const arr = ["This", "Little", "Piggy"];
</span><span class="c3">const first = arr.shift();
</span><span class="c3">console.log(first);
</span><span class="c3">// "This"</span>

(Note that <span class="c5">arr[0]</span> 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 <span class="c5">.pop()</span> and <span class="c5">.shift()</span> 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 <span class="c5">.slice()</span> array method had my back here nicely. It won’t mess with the original array.

This will do us nicely:

<

p class=”c1″><span class="c3">const arr = ["This", "Little", "Piggy"];
</span><span class="c3">const first = arr.slice(0, 1);
</span>const the_rest = arr.slice(1);<sup><a id="cmnt_ref2" href="#cmnt2">
</a></sup><span class="c3">console.log(first); // ["This"] </span><span class="c3">console.log(the_rest); // ["Little", "Piggy"]</span>

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.

About the Author Chris is a web designer and developer. He writes about all things web at CSS-Tricks, talks about all things web at conferences around the world and on his podcast ShopTalk, and co-founded the web coding playground CodePen. More by this Author