So I am trying to solve
" Create a function fizzbuzz that takes one number, n. fizzbuzz should loop through the numbers 1 through n and push each number into the results array using the following rules:
- Push the string "fizz" in place of numbers divisible by 3.
- Push the string "buzz" in place of numbers divisible by 5.
- Push the string "fizzbuzz" in place of numbers divisible by both 3 and 5.
Run the test console.log to check your work. "
My code is listed below
const results = [];
const fizzbuzz = (n) => {
for (let i = 1; i <= n; i++) {
let str = "";
if (i % 3 === 0) str += "fizz"
if (i % 5 === 0) str += "buzz"
if (str === "") str = i;
console.log(str);
}
}
I just don't really know how to change my results so they are inside the array "results". My guess is to use array.push but I do not know where to include it in the code.
You just need to declare your blank array inside your function, use the Array push method, and then return the array at end of function.
const fizzbuzz = (n) => {
const results = [];
for (let i = 1; i <= n; i++) {
let str = "";
if (i % 3 === 0) str += "fizz"
if (i % 5 === 0) str += "buzz"
if (str === "") str = i;
results.push(str);
}
return results;
}
Just for fun, here is better way to solve it using Ternary operators. This method only ever requires 2 checks.
const fizzbuzz = (n) => {
const results = [];
for (let i = 1; i <= n; ++i) {
results.push(
i % 3 === 0
? (i % 5 === 0 ? 'fizzbuzz' : 'fizz')
: (i % 5 === 0 ? 'buzz' : i)
);
}
return results;
}
Contrary to what I said in my comment to @ruleboy's answer I have now provided a very "nerdy" version of fizzbuzz without using the modulus operator at all.
In my snippet I use three counters: i, n3 and n5. The result is not easily readable, therefore I would never recommend using it in any production code. But I thought it might be entertaining to have a look at it nonetheless:
function fizzbuzz(n){
const results = [];
for (let i=1,n3=2,n5=4;
i<=n;
++i,n3--?0:n3+=3,n5--?0:n5+=5) {
results.push(n3?n5?i:"buzz":"fizz"+(n5?"":"buzz"));
}
return results;
}
console.log(fizzbuzz(30))
The expression n3--?0:n3+=3,n5--?0:n5+=5 decrements the counters n3 and n5. Every time any of the counters reaches the value -1 (e. g.: n3--==false) I add the max value to each counter again (3 or 5). Very nerdy - as I already mentioned above! :D
You want to add it to the array every time you would print it, so call the push instead of the console.log():
const results = [];
const fizzbuzz = (n) => {
for (let i = 1; i <= n; i++) {
let str = "";
if (i % 3 === 0) str += "fizz"
if (i % 5 === 0) str += "buzz"
if (str === "") str = i;
results.push(str) //Adding to array instead
}
}