Today, we are going to shop a few heads, ninja style. Who am I kidding, we are actually going to be solving the Slasher Flick bonfire. This exercise will have us write a function that takes an array and a number, and will chop off that number of items from the arrays head and return it.
So we will chop some heads after all, I just wasn’t being explicit enough. We’ve got a few different ways to acomplish this task, but I’ll be showing you one of the solutions as recommended by FCC, the Array.prototype.slice() method.
Array.prototype.slice() (big word eh, prototype, we’ll get to it sometime soon, I’ve conscientiously avoided the term up until now) takes one or two arguments, the start position (keep zero-based indexing in mind) and an optional end position (which is exclusive by the way). Giving it a negative number will make slice count as an offset from the end of the array. If no second argument is given, everything up to the end is taken. If you want a more in-depth explanation, the Mozilla Developer Network is the place you want to be looking at.
Enough chat, let’s get to it. First, we want to check if the second argument wants us to chop more items than what the array actually has, and if true, return an empty array. Then, if the number is lower than one (1), we just return the array, since nothing needs to be chopped off. And finally, we’ll do whatever it needs to be done so that the array get’s it’s head chopped off when none of the other two cases is true.
function slasher(array, howMany) { if (array.length <= howMany) { return []; } else if (howMany < 1) { return array; } return array.slice(howMany); }
And there we go! How about you try doing the same thing by using the splice() method? It’s pretty close to slice(), but not exactly the same. Look at the Mozilla Developer Network documentation to get you going, in the meantime, I’ll show you a ternary operator version of this exercise, look closely:
function slasher(array, howMany) { return array.length <= howMany ? [] : howMany < 1 ? array : array.slice(howMany); }
It may seem a monstruosity, but step by step, it makes sense, it’s just a nested ternary operator chain:
IF array.length <= howMany TRUE return [] FALSE IF howMany < 1 TRUE return array FALSE return array.slice(howMany)
Give it a try! And may the forc… coffee stay with you. You’ll need it!