Slasher Flick - Splice issue

Slasher Flick - Splice issue
0

#1

Hi experts, I am trying to use splice to solve the slasher flick challenge.

Below is the example from MDN, it’s simple enough.

Remove 2 elements from index 2
var myFish = [‘parrot’, ‘anemone’, ‘blue’, ‘trumpet’, ‘sturgeon’];
var removed = myFish.splice(myFish.length - 3, 2);

// myFish is [“parrot”, “anemone”, “sturgeon”]
// removed is [“blue”, “trumpet”]

Below is my code for Slasher Flick:

function slasher(arr, howMany) {
  var resultArray = arr.splice(0 , howMany);
  return resultArray;
}

I am trying to remove ‘howMany’ number of elements starting from 0-index position.

slasher([1, 2, 3], 2); is supposed to return [3]
But it is returning [1,2] instead

Where am I going wrong?

Thanks!


#2

I solved the challenge using shift function, but just want to learn how to use splice


#3


usage: array.splice(start, deleteCount, item1, item2, ...)

so in your code you’re saying start at the 0 index and remove 2 items and store that in a variable called resultArray, so resultArray will have [1,2] as you mentioned. However, the desired value is [3]. Where is [3]? It is still in arr as you have not spliced it out. So instead of returning resultArray we should return something else.

You could also use slice which is different:


Usage: arr.slice(begin, end)


#4

Hi,

Try this one.

function slasher(arr, howMany) {

var x = [];
if ( arr.length > howMany){
x = arr.slice(howMany);
return x;
}
else if
(arr.length <= howMany) {
x = arr.slice(arr.length);
return x;
}

}
slasher([1, 2, 3], 2);