Return divisible by number in an array

Asked

Viewed 848 times

0

I need to traverse an array in Javascript where I should search among the numbers of array the first number divisible by the number that the user will inform and that is non-zero. I tried to create a code, but it is not considering an integer value in the division.

function busca(array, numero)
{
  
  for(i = 0; i < array.length; i++)
    if(array[i] % numero && -! 0)
    
    return array[i]
}

console.log(busca([0, 7, 4, 15, 18, 3, -1, 323, -5], 2)) 

In case when passing the number 2 should return the number 4 of the array, but it is returning the 7.

3 answers

2

function buscarDivisivelPor(array, num) {
  
  for(var i = 0; i <= array.length; i++){
    
    if(array[i] % 2 == 0){
    
      return array[i];
    
    }
  
  }
  
  return console.log("Nenhum número válido encontrado!");
  
}

buscarDivisivelPor([1, 3, 3 ,5, 5 ], 2);

buscarDivisivelPor([1, 2, 3 ,4, 5 ], 2);

2

I’ll just leave here a simpler option:

function busca(array, numero) {
  if (numero === 0) {
    return undefined;
  }
  return array.find(val => val > 0 && val % numero === 0);
}

console.log(busca([0, 7, 4, 15, 18, 3, -1, 323, -5], 2));

function busca(array, numero) {
  if (numero === 0) {
    return undefined;
  }
  return array.find(val => val > 0 && val % numero === 0);
}

console.log(busca([0, 7, 4, 15, 18, 3, -1, 323, -5], 2));

  • I edited your answer to execute the code. If you didn’t like it, no problem, you can remove.

1


There’s a syntax error in the comparison, it doesn’t make any sense, it has things played anyway. Again, without messing with the way you’re doing because it’s a basic exercise and maintaining the best performance:

function busca(array, numero) {
    for (var i = 0; i < array.length; i++) if (array[i] % numero == 0 && array[i] != 0) return array[i];
}

console.log(busca([0, 7, 4, 15, 18, 3, -1, 323, -5], 2));

I put in the Github for future reference.

And yet you have an addiction to not putting ; at the end of the lines, just because it may not mean it’s right, to save a minimal typing a day will do something that doesn’t work and will spend hours trying to figure out why, don’t do it.

  • many thanks again, I will be more attentive with regard to the use of ;

Browser other questions tagged

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