I cannot seem to figure this out whatsoever, I can use console.log(i) and get the return but cant figure out how to return as an array?
Takes a number, max and returns an array that contains every number from 0 to max (not inclusive) that is divisible by either 3 or 5, but not both
function fizzBuzz(max) {
let arr = [];
for(let i = 0; i < max; i ){
if(i % 3 === 0 && i % 7 !== 0){
arr = arr.concat(i);
} else if(i % 3 !== 0 && i % 7 === 0){
arr = arr.concat(i);
}
return arr;
};
fizzBuzz(20);
CodePudding user response:
Using Array.prototype.push
(which is used to add an element to an array) rather than Array.prototype.concat
(which is used to merge an array with another array) is much simpler here. You can also use the XOR operator (^
) instead of writing two if
statements:
function fizzBuzz(max) {
let arr = [];
for (let i = 0; i < max; i ) {
if (i % 3 === 0 ^ i % 5 === 0) {
arr.push(i);
}
}
return arr;
}
console.log(fizzBuzz(20));
CodePudding user response:
Few things wrong in your code, you should use array.push instead of concat and you were missing a }
at the end.
This code should do what you need :) produces an array between 0 and max inclusive and produces an array of numbers that are divisible by 3 or 5 but not both
function fizzBuzz(max) {
let arr = [];
for(let i = 0; i <= max; i ){
if((!(i % 3) && !(i % 5))) continue;
if(!(i % 3) || !(i % 5)){
arr.push(i);
}
}
return arr;
};
console.log(fizzBuzz(20));