Javascript: Problems running a function. How to improve code?

Asked

Viewed 119 times

-1

Hello, I am doing an introductory Javascript course and, although I can print the desired result of the exercise, the platform does not recognize my code. I would like you to help me improve the code or offer me alternatives where I can continue using introductory concepts about Javascript.

The point is: "Program a searchDivisivelWhy you receive two parameters, an array of numbers and a test number, returning as a response the first number of the array that is divisible by the given number and non-zero. If no array number passes in the test, return the text "No valid number found!"".

The errors pointed out by the platform are:

For the array [0, 9, 4, 7, 128, 42, -1, 301, -5] and num = 2 the response should be 4

For the array [0, 9, 4, 7, 128, 42, -1, 301, -5] and num = 7 the response should be 7

For the array [0, 9, 4, 7, 128, 42, -1, 301, -5] and num = 8 the response shall be 128

My code:

function buscarDivisivelPor(array, num)
{
  // Escreva abaixo o seu código:

  var invalido =[];

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

     if (array[i] % num == 0 && array[i] != 0) {

        var valor = 0;
        valor = console.log(array[i]);

         break; 

         return valor;

      } else {

         invalido.push(array[i]);
      } 

      if (array.length == invalido.length){

         return "Nenhum número válido encontrado!";
      } 
   }
} 
console.log(buscarPorDivisivel([0, 9, 4, 7, 128, 42, -1, 301, -5],2));

1 answer

0


Here is a possible solution to your problem.

function buscarDivisivelPor(a, b) {
    for (let i = 0; i < a.length; i++){
        if (a[i] !== 0 && a[i] % b === 0) {
            return a[i]
        }
    }
    return "Nenhum número válido encontrado!"
}

We could implement a version using the filter method of type array, as follows, the function find will resume the first element that meets the condition passed by the auxiliary function:

function buscarDivisivelPor(a,b){
    c = a.find(x => x !== 0 && x % b === 0)
    return c || "Nenhum número válido encontrado!"
}

Browser other questions tagged

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