Login

FizzBuzz

A function that logs Fizz for multiples of 3, Buzz for multiples of 5 and FizzBuzz for multiples of both 3 and 5.

Advanced


Instructions

Write a program that receives an array of positive numbers.And return an array of strings with the same size of the original array.

For multiples of three return "Fizz" instead of the number and for the multiples of five returns "Buzz". For numbers which are multiples of both three and five print "FizzBuzz". If not multiple of three nor five return the number. The output should be an array of strings.

For example, if the input is [1,3,3,5,10,15,7], the output should be ["1", "Fizz", "Fizz", "Buzz", "Buzz", "FizzBuzz", "7"].

Tests
0/2
Function Call:
Expected:
fizzBuzz([1,3,3,5,10,15,7])
[ "1", "Fizz", "Fizz", "Buzz", "Buzz", "FizzBuzz", "7" ]
Run test

Hidden Test
?
Run test

See Solution

Solution

const fizzBuzz = (myArray) => {
    const result = []
    for(const i of myArray){
        if(i%3 === 0 && i%5 === 0){
            result.push("FizzBuzz")
        } else if(i%3 === 0 ){
            result.push("Fizz")
        } else if(i%5 === 0){
            result.push("Buzz")
        } else {
            result.push(i.toString())
        }
    }
    return result
}

Explanation

The operation is simple. We loop through the numbers from 1 to 100 and check if the number is divisible by 3, 5 or both. If it is divisible by 3, we print "Fizz", if it is divisible by 5, we print "Buzz" and if it is divisible by both 3 and 5, we print "FizzBuzz". If none of the conditions are met, we print the number itself.

Complexity Analysis

The time complexity for this algorithm is O(n) where n is the number of elements in the array.

Alternatives

const fizzBuzz = () => {
    Array.from({length: 10}, (_, i) => {
        i++
        let output = ""
        if(i % 3 === 0) output += "Fizz"
        if(i % 5 === 0) output += "Buzz"
        console.log(output || i)
    })
}
Any improvement idea? Share with us!