Guide: Slasher Flick

I have other soluction

function slasher(arr, howMany) {
// it doesn’t always pay to be first
if(howMany>0){
for(var i=0;i<howMany;i++){
arr.shift();
}
}
return arr;
}
slasher([1, 2, “chicken”, 3, “potatoes”, “cheese”, 4], 5);

I had these solutions:

function slasher(arr, howMany) {
  return arr.splice(howMany);
}

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

and

function slasher(arr, howMany) {
  return arr.slice(howMany, arr.length);
}

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

in hindsight I could’ve just used

return arr.slice(howMany);

both produce same answer

In case you were still wondering (this comment is a couple of months old) This happens because you assigned the result of the operation to a variable. See details for splice

Notably:
“Return value
An array containing the deleted elements. If only one element is removed, an array of one element is returned. If no elements are removed, an empty array is returned.”

Thanks for reply! I realize it now - I’ve learned so much over this period, I’m on the ‘No repeats please’ challenge now :slight_smile:

Just having some fun with different refactors - didn’t see anyone try to use other array methods, so here’s another way you could solve this:

function slasher(arr, howMany) {

  // flip array contents
  arr.reverse();

  // remove 'howMany' elements from end
  for (var i = 0; i < howMany; i++) {
    arr.pop();
  }

  // flip array back to original config and return
  return arr.reverse();
}

:slight_smile: cheers!

Chopping of n elements from the head of the array.

function slasher(arr, howMany) {
// it doesn’t always pay to be first

return arr.slice(howMany,arr.length);
}

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

Here is my code. I dont know if it is a good code or not. Im new at coding. I just know it works.

function slasher(arr, howMany) {
if(howMany <= arr.length) {
return arr.splice(howMany, arr.length);
}
return [];
}

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

A solution without using any built in JS functions ( just did it out of curiosity :slight_smile: )

function slasher(arr, howMany) {

var arr2 =[];

for(var i=howMany;i<arr.length;i++)
{
arr2.push(arr[i]);
}

return arr2;
}

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

1 Like

Lol on some challenges I was forking for 3 - 4 hours and this I finished in 5 minutes :DDDDD… You too so fast ?

because you affect to body the result of arr.splice(). In the first code you return arr and in the second you return the value returned by arr.splice().
Know that splice return an array of element that he deleted.

Hello,
here is my code
function slasher(arr, howMany) {
// it doesn’t always pay to be first
if(howMany > arr.length){
arr = [];
}
arr = arr.slice(howMany);
return arr;
}