JavaScript 'SUPER' FizzBuzz

Attempting the classic 'FizzBuzz' challenge in JavaScript this time. Managed to complete the basic challenge and now looking to level up. For those new to FizzBuzz, the goal is to print numbers 1..100 but replace multiples of 3 with Fizz, multiples of 5 with Buzz, and multiples of both with FizzBuzz. What I'm aiming for is a function that takes an array as input and returns the modified array. For instance:

function super_fizzbuzz(array){
    var super_array = [];

    for (var i=0; i<array.length; i++)
    {
        if (array[i] % 15 == 0)
            super_array.push("FizzBuzz");
        else if (array[i] % 5 == 0)
            super_array.push("Buzz");
        else if (array[i] % 3 == 0)
            super_array.push("Fizz");
        else
            super_array.push(array[i]);
    }
    return super_array;
}

console.log(super_fizzbuzz([3,10,15,19]));

The expected result should be ["Fizz", "Buzz", "FizzBuzz", 19], but currently it's returning an empty array. Just worked through this in Ruby successfully, now practicing my JavaScript skills. Any tips would be welcomed!

Answer №1

The issue with your collection lies in its attempt to serve as both an array and an index at the same time. When you set collection = 1, the result is that collection.length evaluates to undefined. This, in turn, means that 1 <= undefined yields false, causing the loop to terminate prematurely without executing. As a result, mega_collection retains its original value of [].

To resolve this problem, consider renaming your loop variable. Additionally, remember that arrays are zero-indexed, meaning they start from 0 rather than 1, and end just before reaching array.length instead of <=.

Answer №2

Presented here:

for (var array = 1; array <= array.length; array++)

You have altered the value of your function parameter, known as "array", by assigning 1 to it. The issue arises because a number does not possess a .length property, preventing the loop from executing any iterations.

To properly iterate through the array values you provide, create an index variable (with a name distinct from the array parameter), and use it to access the elements:

  for (var i = 0; i < array.length; i++) {
      if (array[i] % 15 == 0)
          super_array.push("FizzBuzz");
      // etc

Answer №3

Here is the solution:

function funky_fizzbuzz(array){
          var funky_array = [];

          for (var i=0; i<=array.length-1; i++)
          {
              if (array[i] % 15 == 0)
                  funky_array.push("FizzBuzz");
              else if (array[i] % 5 == 0)
                  funky_array.push("Buzz");
              else if (array[i] % 3 == 0)
                  funky_array.push("Fizz");
              else
                  funky_array.push(array[i]);
          }
          return funky_array;
          }

          console.log(funky_fizzbuzz([3,10,15,19]));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Passing a one-dimensional array into std::thread is not possible

This example is derived from my current project, but I have created a simpler version for demonstration purposes (inspired by Lightness Races in Orbit). #include <thread> #include <iostream> class Foo { Foo(int n = 10) { size_ ...

Can you explain the functionality of the const handleChange = (prop) => (event) => {} function and its significance?

While going through the documentation for MUI, I stumbled upon a new syntax for arrow functions in JavaScript that I haven't seen before. I tried to figure out how it works but couldn't find any information on it. The syntax looks like this: con ...

The positioning of drawings on canvas is not centered

I'm facing an issue while attempting to center a bar within a canvas. Despite expecting it to be perfectly centered horizontally, it seems to be slightly off to the left. What could possibly be causing this discrepancy? CSS: #my-canvas { border: ...

Unable to resolve an unresolved issue with a jquery or javascript bug

I am currently facing some issues with my jQuery code in both Firebug and Chrome's developer tools. Any assistance would be greatly appreciated. Kindly make the necessary updates in the provided fiddle. Please follow this link to access the fiddle: ...

Encountering a Vercel deployment failure due to a TypeError: The 'split' property cannot be read from undefined within several objects

I'm having trouble deploying my web application for the first time and encountering this error on Vercel: TypeError: Cannot read property 'split' of undefined at Object.3qS3 (/vercel/path0/.next/serverless/pages/[collection]/[templateId].j ...

Encountered an AngularJS error: [$injector:modulerr] issue following the implementation of gulp-concat

My Angular app functions properly when I manually load all the scripts, but encounters issues when I attempt to use gulp-concat to consolidate them into a single bundle.js file. Currently, I am loading AngularJS and jQuery from a CDN before the other scri ...

What is the best way to adjust the size of the browser window when opening my page?

I have created a single page scrolling website specifically designed for children. The optimal viewing experience is at 1200 pixels wide. Is there a method to set the window size to that by default when visitors land on the site? ...

Ensuring Form Validity with jQuery for Exclusive Radio Buttons

How can I display an error message when a radio button value is not equal to a specific value? I have a series of yes/no questions and want to show disclaimers under each set of buttons if the value provided is null or different from what is required. Most ...

Learn how to extract an entire table from a website using Kimono Labs, rather than just the first ten rows

Currently, I am utilizing Kimono labs to generate an API for scraping data from the table on this specific website. However, the website only displays the initial 10 rows of the table by default, limiting my API output to just 10 rows. Is there a method to ...

"Enhanced visuals with parallax scrolling feature implemented on various sections for an engaging

With 4 sections, each featuring a background image and text in the middle, I encountered an issue when attempting to have them fixed while scrolling. The goal was for the section below the first one to overlap the one above it along with its text as we scr ...

reconfigure components by resetting settings on a different component

In the interface, I have a section that displays text along with a unique component titled FilterCriteriaList. This component includes custom buttons that alter their color when clicked. My goal is to reset the settings in the FilterCriteriaList component ...

Pass the responsibility to another component or initiate an ajax request in react

I'm currently using fetch for my ajax call, which is located within a handleSearch function in the App component. How can I separate this ajax call into its own component? Coming from Angular 1, where services/factories are used, I'm not sure how ...

What's the best way to ensure a div's height and width are equal when implementing responsive design?

I am currently working on a responsive design and facing challenges in making div's height and width equal. Initially, I set the div's width as a percentage and height as auto, but this caused the divs to not display properly. To resolve this iss ...

Looking for a way to efficiently sort through props in Next.js? Struggling with filtering data within props from componentDidMount in Next.js?

I retrieve data into the props of my component using getStaticProps. However, I need to filter this data before utilizing it in the component. Typically, I would do this in componentDidMount, but it appears that the props are populated after componentDidMo ...

Ways to conceal buttons according to your 'occupation'?

I am currently developing an application and I would like to have certain buttons displayed based on the user's $job. There are four job roles stored in mysql databases: student teacher staff principal, The signup button should only be visible to te ...

The this.setState method does not seem to be properly updating the nested array within the user object. However, when checking the same logic using console.log, the object

When the user selects multiple meals, they are stored in an array of objects inside the user object. Upon clicking submit, the code utilizes setState to update the user's meals as follows: submitAllMeals(arrayOfMeals) { this.setState({ u ...

Issue with combining jQuery-UI and Bootstrap offcanvas components

I've been struggling to understand why my Bootstrap navbar isn't working properly with jQuery-UI. It seems like they're not cooperating, and I can't seem to figure out the issue. If you have any insight into this problem, you'll be ...

Having trouble establishing a connection between the client and server while using Node.js with socket.io, Express, and an HTML file

While following a tutorial on YouTube for creating a simple web game with lobbies/rooms, I encountered an issue. When attempting to establish a connection between the client and server, the expected "a user connected" text did not show up in the console as ...

Guide on incorporating CSS into a JavaScript function

Currently, I am utilizing a jQuery monthly calendar where each day is represented by a cell. When I click on a cell, I can trigger an alert message. However, I also want to modify the background color of the specific cell that was clicked. Unfortunately, ...

What is the best way to implement switchMap when dealing with a login form submission?

Is there a better way to prevent multiple submissions of a login form using the switchMap operator? I've attempted to utilize subjects without success. Below is my current code. import { Subject } from 'rxjs'; import { Component, Output } ...