How to test whole arrays in javascript?

Asked

Viewed 1,085 times

1

Good night!

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, performed on the Chrome console:

When all numbers are even.

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

When all numbers are odd.

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

When a single number is even and should appear true.

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

When a single odd number exists and should appear true, for all others are pairs.

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

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

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

I understood that the function needs to analyze the whole vector and then check if it has at least one number to and return true or false, but I am not able to encode it.

Can anyone help me? Thank you very much!

2 answers

3


Your tie is returning if the last element is even or odd, since the value of the variable condicao is being modified for each element (note that if you pass an empty array, the function will return undefined). If you want the function to return true if there are any even numbers, then you can do just that - when you find the first even number, return true. If the tie (for) finish, that is to say that 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: http://jsfiddle.net/n9tay0hn/

  • It worked out! Thank you so much!

1

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

Using the method every that checks whether all values of an array respect a certain 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

This cool the code gets cleaner and the number of side effects decrease.

Click here to learn more about the method every:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.