Problem about the Intermediate Algorithm Scripting: Drop it

Tell us what’s happening:

if (func(arr[0])) {

In that part why we need to use arr[0] rather than using arr[i]. if we use arr[i] it also stands for arr[0] but why can’t we use arr[i]??

``````
function dropElements(arr, func) {
// drop them elements.
var times = arr.length;
for (var i = 0; i < times; i++) {
if (func(arr[0])) {
break;
} else {
arr.shift();
}
}
return arr;
}

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

User Agent is: `Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0.1 Safari/605.1.15`.

Challenge: Drop it

Hey @mr.chan1997,

It’s like that because if you used `arr[i]` it will change everytime the for loop changes the `i` variable. so it will loop through the 1st item, then delete it. Then it loops through the 2nd item after the first one is deleted here’s what it will visually look like.

``````let arr = [1, 2, 3, 4, 5]
// Loop 1 - i = 0. deletes the first element.
arr[i] -> arr[0] = 1;
console.log(arr) // [2, 3, 4, 5]
// Loop 2 - i = 1. Deletes the second elmnt after the 1st one is deleted
arr[i] -> arr[1] = 3;
console.log(arr) // [2, 4, 5]
``````

Eventually, it goes on until it goes beyond the array size. By using a fixed amount of `0` which is always going to be at the beginning of an array.

Hope this helps understand!

OH～～ thank you

1 Like