Reputation: 41
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
Reputation: 292
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