How to test whole arrays in javascript?

1

Good evening!

I need to create a function that accepts an array of numbers and returns true if it contains at least an even number and false , otherwise.

The code below even does this, SQN:

var ParOuImpar = function(num){
    var i, condicao;
    var True = "True", False = "False";


    for(i=0; i<num.length; i++){

        if ((num[i] % 2) == 0) {
                condicao = True;
            }
        else if ((num[i] % 2) != 0) {
            condicao = False;
        }

    }

    return condicao;
};

Some tests on the Chrome console:

When all numbers are even.

ParOuPrim ([6,6,6]); "True"

When all numbers are odd

ParOuPlus ([1,1,1,1,1,1]); "False"

When a single number is even and should appear true .

ParOpPlus ([16,1,1,1,1,1]); "False"

When there is a unique odd number and it should appear true , since all others are even.

ParOuPrim ([6,6,6,7]); "False"

When the last and first number of the vector are even.

ParOuPrim ([16,1,1,1,1, 16]); "True"

I understood that the function needs to parse the entire vector and then check if it has at least one number to and return true or false, but I'm not sure how to code this.

Can anyone help me? Right away, thank you!

    
asked by anonymous 10.10.2015 / 01:50

2 answers

2

Your loop is returning if the last element is even or odd, since the value of the condicao variable is being modified for each element (note that if you pass an empty array, function will return undefined ). If you want the function to return true if there is any even number, then you can do just that - when you find the first even number, return true . If the loop ( for ) ends, that is, there is no even number in the array, so you can return false .

var ParOuImpar = function(num){
    for (var i = 0; i < num.length; i++) {
        if ((num[i] % 2) == 0) {
            return "True";
        }
    }

    return "False";
}

Example in jsFiddle: link

    
10.10.2015 / 02:19
1

There is a more "functional" alternative to solving this problem.

Using the every method that checks if all values in an array respect a given condition:

const hasPair = (arr) => (
    !arr.every((e) => e % 2 === 1)
);

And you can use it as follows:

hasPair([1, 1, 1]); // false
hasPair([1, 1, 2]); // true

In this way the code gets cleaner and the number of side effects decrease.

Click here to learn more about the every :

    
28.01.2018 / 23:16