I am doing a fizzbuzz challenge in JavaScript where I create a function that accepts a number and returns an array that is the length of the number. When there is a multiple of 3 it will say "fizz" and when there is a multiple of 5 it will say "buzz", and then lastly if it is a multiple of 3 and 5 it will say "fizzBuzz".
[0, 1, 'fizz', 3, 'buzz', 'fizz', 6, 7, 'fizz', 'buzz', 10, 'fizz', 12, 13, 'fizzBuzz']
I do it this way because the array starts at 0. But when I try to do this it ends up getting an output like this:
['fizzBuzz', 1, 'fizz', 3, 'buzz', 'fizz', 6, 7, 'fizz', 'buzz', 10, 'fizz', 12, 13, 'fizzBuzz']
Code:
let someArray = []
const fizzBuzz = () => {
for (let i = 0; i <= 15; i++) {
if (i % 3 === 0) {
someArray.pop()
someArray.push("fizz")
} if (i % 5 === 0) {
someArray.pop()
someArray.push("buzz")
} if (i % 15 === 0) {
someArray.pop()
someArray.push("fizzBuzz")
} else {
someArray.push(i)
}
}
}
fizzBuzz()
I have also seen where you can do it this way:
let someArray = []
const fizzBuzz = () => {
for (let i = 0; i <= 15; i++) {
if (i % 15 === 0) {
someArray.push("fizzbuzz")
} else if (i % 3 === 0) {
someArray.push("fizz")
} else if (i % 5 === 0) {
someArray.push("buzz")
} else {
someArray.push(i)
}
}
}
fizzBuzz()
This gets it right on 3 and 5, but still adds the "fizzBuzz" to the beginning of the array:
['fizzbuzz', 1, 2, 'fizz', 4, 'buzz', 'fizz', 7, 8, 'fizz', 'buzz', 11, 'fizz', 13, 14, 'fizzbuzz']
Is there something that I am doing wrong? and which way would be the correct way to do this? Or if there is a better way to do this?