Iterating and splicing

Currently doing a list of challenges to create methods inside objects. I’ve tried this a million ways but I have reverted my code back to its most simple attempt since I think it will be easiest to pick apart whats going wrong. I seem to be having some serious problems implementing splice() in any kind of loop.

below in the code I wish to iterate through an Array and check if a value is truthy, if so, it is to be deleted and move on to the next index. When it hits a falsy value it should print the array from that value towards the end.

var _ ={
   dropWhile(arr){
     for(i=0; i<arr.length; i++){
       //check if truthy
       if(arr[i]){
         //remove value if truthy
        arr.splice(i,i);
      }else{
        //I am happy to return it as soon as the condition is not fulfilled.
        return arr
   }   
  }
 }
}

let humanArray  =["bob","kyle", "","mike"]
console.log(_.dropWhile(humanArray))

You are usually better off trying to leave the original array unmodified as you are iterating through it and then move the desired items into another array. There are issues with looping through an array that you are modifying and changing length on. It can get complicated and is much easier to create a new array in the function and return the new array. You could loop through the array with a simple for-loop, use forEach, or consider the filter method (the least code probably) if you are comfortable with that array method.

Edit: I realized that you are trying to do something a little different than what I thought at first. Either way, not modifying the original array will simplify the job as index-positions will be the same. You can simply return the array from current index to the last index (array.length - 1) as an option if you loop through it. It may not be necessary to delete items.

1 Like

You were totally right, finding the index and just iterating from that point onwards worked a treat! code below for anyone interested.

var _ ={
   dropWhile(arr){
     //new array for eventual result
      newArr = []
    //value to track index of first falsey value
       index = 0
     for(i=0; i<arr.length; i++){
       //check if truthy
       if(arr[i]){}
       //if not truthy set index
       else{index = i}}
       // iterate from index and push into new array
     for(let j=index; j<arr.length; j++){
              newArr.push(arr[j])
      }
     return newArr
    }
  }

let humanArray  =["bob","kyle", "","mike"]
console.log(_.dropWhile(humanArray))

1 Like