Just need help in identifying what I am doing wrong on this codewar challenge.
I realize this may be easy for some but please note I am just a beginner with Javascript.
Try: for (var i = 0; i < integers.length; i++)
instead of: for (var i = 0; i < integers; i++)
I've found 2 issues inside your code block. You have to run loop over array length instead of entire array otherwise you can use foreach loop. You need to return odd/even value after finishing your loop. Please check updated code as follows, hope it'll help.
function findOutlier(integers){
var even = [];
var odd = [];
for (var i = 0; i < integers.length; i++) {
if (integers[i] % 2 === 0) {
even.push(integers[i]);
} else {
odd.push(integers[i]);
}
}
if (even.length === 1) {
console.log("OK..1");
return even;
} else {
console.log("OK..2");
return odd;
}
}
Another possible way:
function myFunction(integers) {
var odds = integers.filter(function(num) {return num % 2});
var evens = integers.filter(function(num) {return !(num % 2)});
return evens.length == 1 ? evens[0] : odds[0];
}
You can check out this CodePen Demo to test the function in Mocha.
If you want to get the first occurrence without iterating to the last item but without using an imperative code you may do as by using .find()
checking inside if the rightmost bit of n
is 1;
var arr = [2, 4, 0, 100, 4, 11, 2602, 36],
resodd = arr.find(n => n & 1),
reseven = arr.find(n => !(n & 1));
console.log(resodd, reseven);