A simple JS function issue -> Creating a function that will return only even numbers

I am learning JS using open sources and I tried to challenge myself by creating a function that will pull only the even numbers from the given array and return it in a new array that will only contain even numbers.

For example: evensOnly([1,2,3,4,5,6,7,8,9,10]) should return only [2,4,6,8,10];

I have implemented below JS function but it is not giving the correct solution, when I run it on the console, it is saying undefined.

Can someone check and see what I did wrong?

function evensOnly(arr){

    for (i=0; i<arr.length; i++){
        let check = arr[i]%2;
        let evensArray;
        if (check === 0){
            evensArray.push();
        return evensArray;

        }

    }

}
evensOnly([1,2,3,4,5,6,7,8,9,10]);

Upvotes: 0

Views: 56

Answers (1)

Nathan Stockton
Nathan Stockton

Reputation: 292

  • evensArray should be defined before the loop.
  • You need to actually push the value of arr[i] into evensArray.
  • You also need to return a value (in this case, evensArray) after the for loop has completed.

function evensOnly(arr){
    let evensArray = [];
    for (i=0; i<arr.length; i++){
        let check = arr[i]%2;
        if (check === 0){
            evensArray.push(arr[i]);
        }

    }
    return evensArray;

}
alert(evensOnly([1,2,3,4,5,6,7,8,9,10]));

Upvotes: 1

Related Questions