I try to receive only even numbers, summing values from two arrays. If the result cannot be even, it should return one even value without summing being executed.
These are two arrays:
var a = [-2, 10, 30, 50, 11, 22, 100];
var b = [10, 8, 22, 5, 11, -5];
So, the result should be :
[8, 18, 52, 50, 22, 22, 100],
which stems from the following:
-2 + 10 = 8 (even), 10 + 8 = 18 (even),
30 + 22 (even), 50 + 5 = 55 (not even),
so 50 should be, because it is even, 11 + 11 = 22 (even), 22 + (-5) = 17 (not even), so 22 should be, because it is even, 100 is even.
I have the code, but it returns boolean "true" instead of 50 and second 22. How that can be fixed?
function sumArray(a, b) {
var c = [];
for (var i = 0; i < Math.max(a.length, b.length); i++) {
c.push((a[i] || 0) + (b[i] || 0));
}
return c;
}
var a = [-2, 10, 30, 50, 11, 22, 100];
var b = [10, 8, 22, 5, 11, -5];
var numbers = sumArray(a, b);
function OnlyEvens(numbers) {
;
var evens = [];
for(var i = 0; i < numbers.length; i++){
if(numbers[i]%2 == 0) evens.push(numbers[i]);
else (evens.push (a[i] % 2 == 0 || b[i] % 2 == 0))
}
return evens
}
var check = OnlyEvens(numbers);
console.log(check)
elsebranch produces. If you compare something (a[i] % 2 == 0) the result will be eithertrueorfalse.