# Stuck in the Drop It Algorithm

Stuck in the Drop It Algorithm
0

#1

Hello, I got stuck at this algorithm.

Given the array arr , 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.

Then return the rest of the array once the condition is satisfied, otherwise, arr should be returned as an empty array.

How I see the problem:

1. I need to create a new array where I can store each item from the original one, in order not to mutate the original one.
2. Loop through it removing each item when the function returns false.
3. When the function returns true - return the array.
4. Return the array at the end if it’s empty.

Any tips would be highly appreciated.

function dropElements(arr, func) {
let newArr = arr;
for(let i = 0; i < newArr.length; i++){
if(!func(newArr[i])){
newArr.splice(0, 1);
} else if(func(newArr[i])){
return newArr;
}
}
return newArr;
}

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

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36.

#2

Hi.

1. There is no need to create a new array, we don’t care about mutating the original one in this challenge. You can just operate on arr.
2. Be careful with your indexes! Each time you are dropping an element from your array, you need to decrement the index of your for loop too. Let’s take an example:

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

i = 0: 1 >= 3 is false so we remove it using splice.
i = 1: here your array is currently [2, 3, 4] since you drop 1 from it. But your index isn’t updated. So instead of choosing arr[0] which is 2, it will choose arr[1] which is 3. As 3 >= 3 is true, then you return your new array which is [2, 3,4 ] instead of [3, 4].

One way of fixing it is by decrementing i just after you splice the array:

newArr.splice(0, 1);
i--;

You can also have other solutions. For example, you can use a while loop instead of for.

Hope it helps!

#3

Thank you, dear friend. Helped a lot!

You are the best!!!