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, I stopped in my tracks! Not 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:
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 a 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 alone! The <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:
https://codepen.io/sdras/details/gogVRX
Click here to build your next great project on Media Temple.