Hi guys!
Re Intermediate Algorithms the ‘Drop It’ exercise…
I came up with a nice, neat (by my newbie-standards) bit of code, starting with a for-loop, including the usual " i < arr.length " instruction. It worked beautifully! EXCEPT for the case [1, 2, 3, 4, ] , func(n) {n > 5} . I couldn’t understand why it failed in that one case.
When I created the var “times = arr.length;”, then substituted “times” for the arr.length in the for-loop, bingo! All tests passed. Can someone tell me why this simple changed made such a telling difference. My original code:
~~
function dropElements(arr, func) {
for (var i = 0; i < arr.length; i++) {
if (!func(arr[0])) {arr.shift(arr[0]);
} else {arr.slice(arr[0]);
}
} return arr;
}
console.log(dropElements([1, 2, 3, 4], function(n) {return n > 5; }));
// console output [ 3, 4 ] ~~
Many thanks
PeterL