0

I have to go through the following array and find the number that isn't a multiple of eight (58 at the end). I've been trying to figure out how to do it but nothing I tried really worked.

var multiplesOfEight = [8,16,24,32,40,58];

I tried this

var multiplesOfEight = [8,16,24,32,40,58];
if (multiplesOfEight % 8 === 0) {
    console.log("Multiple of 8");
} else {
    console.log("Wrong number");
}

and it just logs "Wrong number", I was expecting it to repeat "multiple of 8" five times and then wrong number but I guess that if/else is taking the array as a whole or something? An explanation of what exactly is happening with this if/else would also be appreciated.

1
  • you should use a for loop! Commented Apr 24, 2015 at 2:37

6 Answers 6

1
for(var i=0;i<multiplesOfEight.length;i++){
if (multiplesOfEight[i] % 8 === 0) {
    console.log("Multiple of 8");
} else {
    console.log("Wrong number");
}
} 
Sign up to request clarification or add additional context in comments.

2 Comments

Jus modified it.. Typo
Consider console.log(mutiplesOfEight[i] % 8? 'Mulitple of 8' : 'Wrong number'). ;-)
0

You can accomplish this using a for loop, however you don't even need to store the array in a separate variable. With this syntax, you can integrate the array right into the for loop itself:

for (var multiple of [8,16,24,32,40,58]) { 
    if (multiple % 8 === 0) {
        console.log("Multiple of 8");
    } 
    else {
        console.log("Wrong number");
    }
}

http://jsfiddle.net/IronFlare/37ju75c6/

Comments

0
var multiplesOfEight = [8,16,24,32,40,58];
for(var i=0;i<multiplesOfEight.length;i++){
if (multiplesOfEight[i] % 8 === 0) {
    console.log("Multiple of 8");
} else {
    console.log("Wrong number");
}
} 

1 Comment

You want to compare multiplesOfEight at i
0

Simpler with forEach statement (open console of browser to view result when running snippet):

[8,16,24,32,40,58].forEach(function(i) {
  if (i % 8 === 0) console.log(i + " is multiple of 8");
  else console.log(i + " is wrong number");
});

Comments

0

You need to check whether each element of the array modulo 8 equals 0.

An option is to use Array#forEach.

var multiplesOfEight = [8,16,24,32,40,58];

multiplesOfEight.forEach(function(num, index){
   if (num % 8 === 0) {
       console.log("The number " + num + " at index " + index + " is divisible by 8");
   } else {
       console.log("The number " + num + " at index " + index + " is a wrong number");
   }
});

Comments

0

What happens if you iterate over the numbers? ;)

[8, 16, 24, 32, 40, 58].forEach(function(n) {
  if(n % 8 == 0) 
     console.log(n + " is multiple of 8");
  else
     console.log(n + " is not multiple of 8");
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.