Drop it - why can't I test for elements that pass function and push them to new array

Hi

I can follow the solution to this problem.

However, when I started coding by myself, I tried to push the elements that passed the function to a new array.

I don’t understand why I can’t do this.

Your code so far


function dropElements(arr, func) {
  
  
  // for loop with if statement to splice

let answer = [];

  for(let i = 0; i < arr.length; i++){
    if (func(arr[i])){
        answer.push[i];
    }
  }
  return answer;
}

console.log(dropElements([1, 2, 3], function(n) {return n < 3; }));

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36.

Link to the challenge:

That is not now push() works.

arr.push(something)

Also, I’m not sure you meant to push the index, but the element push(arr[index])

1 Like

Thank you

Back on track now

SOLVED: I understand it now.

The challenge isn’t looking for all values that pass the condition in the function. It wants the first element of arr to pass the condition in the function only.

My code is working for all of the examples except the second and the last.

I think I don’t properly understand the challenge.

In the second example, why should the answer include zero in the array when the condition in the function is return n === 1 ?

Similarly, in the final example, why should the answer include 2 in the array when the condition in the function is return n > 2 ?

function dropElements(arr, func) {
  
  
  // for loop with if statement to splice

let answer = [];

  for(let i = 0; i < arr.length; i++){
    if (func(arr[i])){
        answer.push(arr[i]);
    }
  }
  return answer;
}