[SOLVED] Why slice is skipping one Element, Drop It Challenge

[SOLVED] Why slice is skipping one Element, Drop It Challenge
0

#1


function dropElements(arr, func) {
  // Drop them elements.
  var newArr = [];
  for (var i = 0; i < arr.length; i++){
    
    if(!func(arr[i])) { newArr = arr.slice(i+1); }
   
  }
  
  return newArr;
}

dropElements([1, 2, 3, 9, 2], function(n) {return n > 2;});
dropElements([1, 2, 3], function(n) {return n > 0;});

The Result should be [3,9,2] i am getting an empty array [].

My Logic is enter the If statement if (Different False) and Slice when func is false


#2

May I ask why slice ? You are continually changing contents of newArr by using slice and not adding values to it. IMO, you are better off using push since you already have an empty array newArr you can add conditional values returned from func.


#3

Yes, i am using slice because it uses less iterations than a for loop with arr.length, Once the function is true the newArr is equal to the rest of the array. Now it works great.

I used break to stop the loop from continuing. the newArr is built only once when the function is true.

You can see the solution :

function dropElements(arr, func) {
  // Drop them elements.
  var newArr = [];
  for (var i = 0; i < arr.length; i++){
    
    if(func(arr[i])) { newArr = arr.slice(i);  break;}
   
  }
  
  return newArr;
}

dropElements([1, 2, 3, 9, 2], function(n) {return n > 2;});

#4

I see, I had forgotten the instructions of the challenge to stop at the first element that did not satisfy the condition

iterate through and remove each element starting from the first element (the 0 index) until the function func returns true when the iterated element is passed through it.

Actually I also had solved it using slice and break too.