wongwy
October 13, 2017, 7:01am
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!
wongwy
October 13, 2017, 7:10am
2
I solved the challenge using shift function, but just want to learn how to use splice
v-lai
October 17, 2017, 7:08pm
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)
2 Likes
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);