Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

213
Views
FizzBuzz is it possible make my solution shorter?

I tried to make 3 conditions in one array.forEach, but this give me incorrect output. Is it possible to short my code to one array.forEach? Have 3 conditions inside it?

var array = []; // create empty array
for (var i = 1; i < 101; i++) {
  array.push(i); // write in array all values of i, each iteration
}

array.forEach((number) => {
  if (array[number] % 3 === 0 && array[number] % 5 === 0) {
    array[number] = "FizzBuzz";
  }
});

array.forEach((number) => { //  
  if (array[number] % 3 === 0) {
    array[number] = "Fizz";
  }
});

array.forEach((number) => {
  if (array[number] % 5 === 0) {
    array[number] = "Buzz";
  }
});

for (let i = 0; i < array.length; i++) { //output array elements
  console.log(array[i]);
}
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

First pointer: that's a lot of whitespace.

Second pointer, rather than creating an array then cycling through that array, you can do it all in one loop, using the if....else block; something like this:

for (var i = 1; i < 101; i++) {
   if (i % 3 === 0 && i % 5 === 0) {  
        console.log("FizzBuzz");
   }
   else if (i % 3 === 0) {
        console.log("Fizz");
   }
   else if (i % 5 === 0) {
        console.log("Buzz");
   }
   else {
        console.log(i);
   } 
}
about 4 years ago · Juan Pablo Isaza Report

0

You are "walking over" the Array multiple times.

IMHO the most important Array Method to learn is Map:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

Which "walks over" the Array and returns a new value for that Array index

let arr = Array(100)
  .fill((x, div, label) => x % div ? "" : label) //store Function in every index
  .map((func, idx) =>
    func(++idx, 3, "Fizz") + func(idx, 5, "Buzz") || idx
  );
document.body.append(arr.join(", "));

fill takes a single Object, it is not executed 100 times!
Since JavaScript Functions are Objects this code declares a function once

Note the ++idx because we want to start at 1, not 0

In JavaScript ""+"" is a Falsy value, thus it returns the idx value for non-FizzBuzz numbers

More Array Methods explained: https://array-methods.github.io

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!