Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

recursion in array to find odd numbers and push to new variable

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)
if i don't write 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

like image 764
Zum Dummi Avatar asked Jan 08 '19 10:01

Zum Dummi


People also ask

How do you return an odd number from an array?

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.

How do you add odd numbers to an array?

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);


1 Answers

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);
like image 103
Nina Scholz Avatar answered Oct 10 '22 21:10

Nina Scholz