Im confused by what I just did to complete Drop it

also this is a solution for Drop It so be fore warned before clicking it!

function dropElements(arr, func) {
  // Drop them elements.
  let i = 0;
  while( i < arr.length+3 ){
  i++;
  
  
  if(func(arr[0])){
    break;
  }else{
    arr.shift();
  }
}
return arr;

}

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

If I didn’t add plus three too my arr.length call it would not create the empty array, what is another way I could have done it to make that work more cleanly?

The issue is that arr.length is being decremented each time you use the shift method, which will result in longer arrays not working. See logs below:

function dropElements(arr, func) {
  let i = 0;
  while (i < arr.length + 3) {
    console.log(
      `i = ${i} arr.length = ${arr.length} arr.length + 3 = ${arr.length + 3}`
    );
    i++;
    if (func(arr[0])) {
      break;
    } else {
      arr.shift();
    }
  }
  return arr;
}

Having trouble thinking of a way to make this approach work, i’ll let you know if I think of something.

If you try finding the index that the array should be cut at, rather than shifting numbers off of it you could use that approach, and then return the array sliced at the index you found.

Spoiler solution of that approach below:

function dropElements(arr, func) {
  let i = 0;
  let sliceIndex;
  while (i <= arr.length) {
    if (func(arr[i]) || i === arr.length) {
      sliceIndex = i;
      break;
    }
    i++;
  }
  return arr.slice(sliceIndex);
}
1 Like

that actually makes a lot of since looking at it that way, thank you! sorry I took so long to reply I guess notifications were off