Returning numbers divisible by 3 within an array using a For Loop?

  • A+

I am trying to return numbers to the console that are divisible by 3 within the array below, using a for loop as seen below.

It is returning numbers 2-9 into the console, but not the ones divisible by 3? I am stumped? What am I doing wrong?

var numbers = [1,2,3,4,5,6,7,8,9,10]  for(var i = 0; i < numbers.length; i++) {     if(i % 3){        console.log(numbers[i]);     } } 

The if statement branches based on the result of the conditional statement. if(i % 3){ will return true anytime the result of the modulo operation is not 0 because any non-zero number converts to true.

The statement should be: if(i % 3 === 0){ because you only want to branch into the true section if you divide by 3 and the remainder is 0.

Next, you are using your loop index as the number to operate on, but you need to use the array item with the index of your loop counter numbers[i], not i.

var numbers = [1,2,3,4,5,6,7,8,9,10]  for(var i = 0; i < numbers.length; i++) {     if(numbers[i] % 3 === 0){        console.log(numbers[i]);     } }

Also, a simpler approach here may be to use Array.filter(), which loops over the array and returns a new array with the values you specify:

var numbers = [1,2,3,4,5,6,7,8,9,10];  var results = numbers.filter(function(num){   return num % 3 === 0; });  console.log(results);


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: