I tried to recursion those arrays to find odd/even numbers then push
them to newArr but the result, not an array, that result is the string with numbers the result after found the odd/even numbers.
this is the code i wrote,
function odd(nums){
var result = [];
if(nums.length === 0) {
return result;
} else if (nums[0] % 2 === 0){
result.push(nums[0])
// return odd(nums.slice(1))
};
return result + odd(nums.slice(1));
};
var arr = [1,8,3,4,4,5,9,13,13,9,10];
var print = odd(arr);
console.log(print)
return result + odd(nums.slice(1));
the result nothing / undefined
,
can anyone help me to explain why that result in a string, not an array I wanted
To find the odd numbers in an array, we can call the Array filter() method, passing a callback that returns true when the number is odd, and false otherwise. The filter() method creates a new array with all the elements that pass the test specified in the testing callback function.
Two good solutions: int [] x = new int[0]; LinkedList<Integer> even = new LinkedList<Integer>(), odd = new LinkedList<Integer>(); for(int num: x) if (x & 1 == 1) odd. add(num); else even. add(num);
You need to concat
arrays. +
does only work for strings or for numbers.
BTW, after block statements { ... }
, you do not need a semicolon.
function odd(nums){
var result = [];
if (nums.length === 0) {
return result;
}
if (nums[0] % 2 === 0) {
result.push(nums[0]);
}
return result.concat(odd(nums.slice(1)));
}
var arr = [1, 8, 3, 4, 4, 5, 9, 13, 13, 9, 10];
var print = odd(arr);
console.log(print);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With