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

  • A+
Category:Languages

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

 


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

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: