CaliCap
CaliCap

Reputation: 31

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

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]);
    }
}

Upvotes: 3

Views: 7461

Answers (5)

Scott Marcus
Scott Marcus

Reputation: 65806

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);

Upvotes: 10

Narendra Jadhav
Narendra Jadhav

Reputation: 10262

ES6

You can also achieve by using Unary Negation Operator (Exclamation Mark) with help of reduce()

DEMO

var numbers = [1,2,3,4,5,6,7,8,9,10]

console.log(numbers.reduce((r,v)=>!(v%3)?r.concat(v):r,[]))
.as-console-wrapper {max-height: 100% !important;top: 0;}

With help of filter()

DEMO

var numbers = [1,2,3,4,5,6,7,8,9,10]

console.log(numbers.filter(v=>!(v%3)))
.as-console-wrapper {max-height: 100% !important;top: 0;}

Upvotes: 0

sourabh
sourabh

Reputation: 48

One thing that you are doing wrong is that you are using i instead of numbers[i] and secondly you are not comparing it to 0. It should be something like:

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]);}}

Upvotes: 0

Matt
Matt

Reputation: 35211

The problem is your if statement. Please see the example.

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]);
    }
}

Upvotes: 0

Zohaib Ijaz
Zohaib Ijaz

Reputation: 22885

var numbers = [1,2,3,4,5,6,7,8,9,10];

numbers.forEach(n => {
  if (n % 3 === 0) console.log(n);
});

Upvotes: 1

Related Questions