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:
- 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.
- Loop through it removing each item when the function returns false.
- When the function returns true - return the array.
- Return the array at the end if it’s empty.
Any tips would be highly appreciated.
Your code so far
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; });
Your browser information:
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
.
Link to the challenge: