var arr = [4, 5, 7, 8, 14, 45, 76];
function even(a) {
var ar = [];
for (var i = 0; i < a.length; i++) {
ar.push(a[2 * i + 1]);
}
return ar;
}
ale
Even if this question is quite old, I would like to add a one-liner filter:
Odd numbers: arr.filter((e,i)=>i%2)
Even numbers: arr.filter((e,i)=>i%2-1)
A more 'legal' way for even numbers: arr.filter((e,i)=>!(i%2))
There's no need to check with i%2===1
like sumit said; as mod 2
already returns a 0 or a 1 as numbers, they can be interpreted as boolean values in js.
You need to test the elements for evenness like this:
var arr = [4,5,7,8,14,45,76];
function even(a){
var ar = [];
for (var i=0; i<a.length;i++){
if (a[i] % 2 === 0)
{
ar.push(a[i]);
}
}
return ar;
}
alert(even(arr));
%2 is the modulo operator, it returns the remainder of integer division.