Discovering the common multiples of two numbers within an array by utilizing the .forEach() method in JavaScript

I have been tasked with looping through an array using the .forEach method in order to return all the values. If any of the numbers are a multiple of 3 or 5, or both 3 and 5, that number must be returned as a string. Here is my current code:

let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 
14, 15];
let count = [];
arr.forEach((item) => {
count[item] = item;
if (count[item] % 3 === 0) {
count[item] = "Fizz";
} else if (count[item] % 5 === 0) {
count[item] = "Buzz";
} else if (count[item] % 3 === 0 || count[item] % 5 === 0) {
count[item] = "FizzBuzz";}
return count;});
console.log(count);

The challenge I am facing is that I am struggling to get it to return the final string "FizzBuzz" and also prevent the initialization of the count variable from displaying in the console.

As a beginner in JS, I would appreciate an explanation of the solution wherever possible.

Attached below are images of the outputs:

result

Expected output

Edit:

I should mention that this exercise is part of an assignment, so I must use the forEach method. This sets it apart from another question where a for loop was utilized instead.

Answer №1

  • I streamlined the if statement by using guard clauses

  • An effective approach is to utilize Array.forEach() with the index parameter for better organization

let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 
  14, 15];

arr.forEach(function(element, index) {
  if (element % 5 === 0 && element % 3 === 0) return arr[index] = "Fizz-Buzz"
  if (element % 5 === 0) return arr[index] = "Buzz"
  if (element % 3 === 0) return arr[index] = "Fizz"
})

console.log(arr)

It's important to note that JavaScript arrays start indexing at 0 ... therefore, count[item] = [item] can leave an undefined spot at count[0]. It's recommended to make use of the index argument in your forEach function from the beginning

Below is the code presented without guard clauses:

arr.forEach(function (element, index) {
  if (element % 5 === 0 && element % 3 === 0) {
    arr[index] = "Fizz-Buzz"
  } else if (element % 5 === 0) {
    arr[index] = "Buzz"
  } else if (element % 3 === 0) {
    arr[index] = "Fizz"
  }
})

Answer №2

To effectively handle the "FizBuzz" scenario before processing "Fizz" and "Buzz" individually, it is recommended to utilize .map instead of .forEach. The advantage of using .map in this situation is that it returns each element directly, eliminating the need to create a new empty array.

const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

const res = arr.map(el => {
    if(el % 3 === 0 && el % 5 === 0)
        return "FizBuzz"
    else if (el % 3 === 0)
        return "Fizz"
    else if (el % 5 === 0)
        return "Buzz"
    else return el
})

console.log(res)

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

Dealing with errors such as "Failed to load chunk" can be resolved by implementing lazy-loading and code-splitting techniques

Our team is currently working on a Vue.js application using Vue CLI 3, Vue Router, and Webpack. The routes are lazy-loaded and the chunk file names include a hash for cache busting purposes. So far, everything has been running smoothly. However, we encoun ...

Exploring the use of the new keyword to create pointer arrays in C++

Can you explain the significance of the following code snippet? int **matrix = new int*[n]; What distinguishes matrix from int*[n] in this context? ...

Error when sending Angular 4 GET request with multiple Headers results in a 400 bad request code

I've been attempting to perform a POST request with headers in order to receive a response. The Angular code snippet I'm currently using for this request is shown below: const headers = new HttpHeaders({ 'Content-Type': 't ...

Pattern matching for directory path excluding the filename

Looking for assistance with creating a JavaScript regex pattern to validate text input as folder paths only, excluding the filename. Can someone provide guidance on this? For example: folder1/folder2/folder3 => valid folder1/folder2/filename.txt1 =&g ...

Struggling to integrate Ajax with Angular framework

Looking to learn Angular. Attempting to integrate Angular with AJAX calls. Whenever I try to access http://localhost:9091/jerseyservlet/jerseyrest/org/orgId/DEY using a browser or any REST client, the following response is displayed: <users> & ...

Switching ng-Idle countdown time from seconds to minutes is possible by adjusting the configuration settings

I have implemented ng-idle in my application, where the warning popup appears after 10 seconds with the message: "Your session will be close in 10 seconds" However, I need to change this to minutes. The session should be closed in 5 minutes instead. How ...

Tips for creating a responsive carousel slider for images

No matter how much I've tried, I can't seem to find a solution on how to make my image responsive along with the caption. Below is my HTML code: <section id="banner"> <div class="banner-bg"> <div class="banner-bg-item ...

AngularJS: iterating through POST requests and passing each index into its corresponding response

Using AngularJS, I am attempting to execute multiple http POST requests and create an object of successfully finished requests. Here is a sample code snippet: var params = [1, 2, 3], url, i, done = {}; for (i in params) { url = '/dir ...

AngularJS allows for the passing of a function value into another function

Is there a way for me to pass a value from one function to another? Here is an example of what I am trying to achieve: HTML <div> <li ng-repeat="language in languages" ng-click="myFirstFunction(firstValue) {{lang ...

Can I access properties from the index.html file within the Vue.js mount element?

<!DOCTYPE html> <html lang=""> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="widt ...

How to retrieve the image source from a block using jQuery

Currently, I am working on developing a slider for my webpage using jquery's "Cycle" plugin. However, I have encountered an issue with accessing the image sources used in the slider. To provide more context, here is a snippet of code from the 'he ...

Check if the page has been loaded using Jquery

Can anyone share a helpful strategy for initiating a function in JavaScript that only begins once the entire page has finished loading? ...

JavaScript function that shows the name of an individual extracted from a specific file

Hey there, currently I'm diving into a javascript tutorial and exploring ways to display a person's name along with their birthday on this historical day. <script type="text/javascript"> document.write("Today is <br/&g ...

Parsing an XML array using XSLT and implementing a universal template for nested elements to convert from XML to JSON

My task involves converting a number of XML files into the appropriate JSON format using XSLT. While I've managed to convert everything successfully, one issue remains with arrays. I need to create templates that are versatile enough to handle any sce ...

Issue with AngularJS ng-model not updating the value of a hidden input

My goal is to transmit form data using hidden input like this: <input type="hidden" required ng-model="formHolder.template[position].itemKey[itr]" ng-value="[[ formItem ]]" /> The value of formItem can be any string. Issues arise when the strings c ...

Searching for 10 random data records within a collection of 100 in MongoDB

Can MongoDB retrieve a specific number of random documents in one query? For example, I currently load all the documents in the collection on the JavaScript side, which is inefficient. I'm wondering if there's a better way to achieve this with a ...

nyroModal automatically adapts its dimensions according to the size of the webpage, not the size of

A situation has arisen with a link that opens an image using nyroModal. While everything is functioning correctly, the Modal window appears in the center of the page instead of aligning with the middle of the browser window. As a result, only the upper por ...

Retrieving data response post upload with JQuery and an HTML5 Uploader

After uploading an image and receiving a successful post response with the id of the inserted image, how can I insert this response as a data-id attribute within a a tag? Where in the function does this process occur? Here is the function: function img_ ...

Iterate through an ajax function by employing promises

I have recently delved into the world of es6-promises and I'm struggling to fully grasp its concepts. In my project, I am attempting to retrieve data through an ajax call and keep looping until all data is fetched (essentially pagination). Below is t ...

Ways to store a JSON string in a variable

When utilizing the ajax function, I am able to retrieve my JSON string. Here is an example: $.ajax({ type: "POST", url: "http://localhost/./Service/GetPageInfo", dataType: "json", contentType: 'application/json' ...