Returning an odd or even number from array

后端 未结 4 561
谎友^
谎友^ 2021-01-25 02:06

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.

相关标签:
4条回答
  • 2021-01-25 02:34

    Try: for (var i = 0; i < integers.length; i++)

    instead of: for (var i = 0; i < integers; i++)

    0 讨论(0)
  • 2021-01-25 02:35

    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;
        }
    }
    
    0 讨论(0)
  • 2021-01-25 02:45

    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.

    0 讨论(0)
  • 2021-01-25 02:46

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

    0 讨论(0)
提交回复
热议问题