FizzBuzz is it possible make my solution shorter? - javascript

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]);
}

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);
}
}

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

Related

Fizzbuzz function logic not working: Output order is incorrect and logic doesn't make sense

I'm creating a simple Javascript Function that should write the numbers from 1 to n. For any multiplier of 3, it outputs "Fizz", instead of multiplers of 5 you output "Buzz", and if they happen at the same time, you should use "FizzBuzz". The output of the function should be a mixed array of numbers and strings.
My current code is outputting the array order and expected values incorrectly.
function fizzbuzz (n) {
let arr = [];
for (let i = 0; i < n; i++){
//if i is a multiple of 3 then Fizz
if(i % 3 === 0) {
arr.push("Fizz");
}
//if i is a multiple of 5 then Buz
if(i % 5 == 0) {
arr.push("Buzz");
}
//if both then FizzBuzz
if(i % 3 === 0 && i % 5 === 0) {
arr.push("FizzBuzz");
}
else {
arr.push(i);
}
}
return arr;
}
When fizzbuzz(7) is entered, I expect the output to look like this:
[0, 1, 2, "Fizz", 4, "Buzz", "Fizz", 7];
Instead, it's this:
["Fizz","Buzz","FizzBuzz",1,2,"Fizz",3,4,"Buzz",5,"Fizz",6]
Could someone enlighten me to the fault in my logic? This should be more straightforward than I had originally thought.
You have three different if statements there, the last one having an else clause, instead of one continuous if statement with several else if clauses. Note that for this to work properly you need to first test the "FizzBuzz" condition:
function fizzbuzz (n) {
let arr = [];
for (let i = 0; i < n; i++){
//if both then FizzBuzz
if(i % 3 === 0 && i % 5 === 0) {
arr.push("FizzBuzz");
}
//if i is a multiple of 3 then Fizz
else if(i % 3 === 0) { // Changed to an else-if
arr.push("Fizz");
}
//if i is a multiple of 5 then Buz
else if(i % 5 == 0) { // Changed to an else-if
arr.push("Buzz");
}
else {
arr.push(i);
}
}
return arr;
}
Quick note regarding the expected output - 0 is divisible by 3 and 5 (and other other integer, for that matter), so the first element of the array should be "FizzBuzz"

Why code works when I write myArray[i] and not when I save myArray[i] in a variable?

I want to populate an empty array with the classical fizzbuzz game (numbers from 1 to 100, when a number is divisible by 3 print 'Fizz, divisible by 5 print 'Buzz', divisible by both 3 and 5 print 'Fizzbuzz'). The problem is, when I write code like in the first portion of code below saving my array[i] in a more convenient variable my if-else if statement doesn't work, only normal numbers are printed; but when I use array[i] instead of a variable everything works fine, as you can see in the second portion of code, where 'Fizz', 'Buzz', 'FizzBuzz' overwrite the normal numbers. They should be the same thing right?
First portion of code with a variable instead of array[i]
var numberArray = [];
var number = 0
for (var i = 0; i < 100; i++) {
number += 1;
thisNumber = numberArray[i];
numberArray.push(number);
if (number %3 ==0 && number %5 ==0) {
thisNumber = 'FizzBuzz';
} else if ( number %3 ==0 ) {
thisNumber = 'Fizz';
} else if ( number %3 ==0 ) {
thisNumber = 'Buzz';
}
}
console.log(numberArray);
Second portion of code with array[i] instead of a variable
var numberArray = [];
var number = 0
for (var i = 0; i < 100; i++) {
number += 1;
numberArray.push(number);
if (number %3 ==0 && number %5 ==0) {
numberArray[i] = 'FizzBuzz';
} else if ( number %3 ==0 ) {
numberArray[i] = 'Fizz';
} else if ( number %3 ==0 ) {
numberArray[i] = 'Buzz';
}
}
console.log(numberArray);
Reassigning a variable, by itself, never has any side effects (except in the most rare situations which aren't worth worrying about). Doing thisNumber = 'FizzBuzz'; does not change anything about how thisNumber may have happened to be used in the past.
Push after assigning to thisNumber. You also want to push thisNumber, not number.
You also need to change the final % 3 to % 5 - you're currently testing % 3 twice.
var numberArray = [];
for (var i = 0; i < 100; i++) {
let thisNumber = i;
if (i % 3 == 0 && i % 5 == 0) {
thisNumber = 'FizzBuzz';
} else if (i % 3 == 0) {
thisNumber = 'Fizz';
} else if (i % 5 == 0) {
thisNumber = 'Buzz';
}
numberArray.push(thisNumber);
}
console.log(numberArray);
In JavaScript a variable is just a reference to an object and an assignment changes where it points to. In
thisNumber = 'FizzBuzz';
you create a new string object and reference it with thisNumber. In
numberArray[i] = 'FizzBuzz';
you modify the i-th element of the array numberArray.
You can't create a reference to an array element and modify it with an assignment. That's not possible in JavaScript.

How to display list of numbers based on condition in javascript

I would like to know how to get the list of numbers based on two condition
number should be divisible by 3
number should not end with 3
How to implement the list within 50 numbers in javascript
Expected Output
6,9,12,15...45
My attempt
function getNumbers() {
var result = [];
for (var i = 0; i < 50; i++) {
if (i % 2 == 0) {
return
} else {
result.push(i);
return result.toString()
}
}
}
console.log(getNumbers())
This seems to work to specs - your specs says it should start at 6 and not at 1
const numbers = [...Array(50).keys()].
filter(num => num !== 0 && num%3 === 0 && !String(num).endsWith("3"))
console.log(numbers)
NOTE: You can change [...Array(50).keys()] to [...Array(50).keys()].slice(1) if you want to avoid the test for 0
You can do that with a check if the modulo of 3 is 0 and the modulo of 10 is not 3. If you want to beautify the code you can combine this answer with mplungjan answer, but i wanted to show a mathematical alternative of the !String(num).endsWith("3") method provided by mplungjan.
I started your iteration at 1 instead of 0 to avoid 0 being put into the array. I also corrected your return statements.
function getNumbers() {
var result = [];
for (var i = 1; i < 50; i++) {
if (i % 3 === 0 && i % 10 !== 3) {
result.push(i);
}
}
return result;
}
console.log(getNumbers())

Javascript. If array has 3 odds in a row, print "odd". if array has 3 evens in a row - print "even"

I'm new to javascript and I'm looking for some help with the following algorithm.
If array has 3 odd numbers in a row, print "odd". if array has 3 even number in a row - print "even".
function oddsAndEvens (arr) {
for(i=0; i < arr.length; i++) {
if(arr[i]%2==0 && arr[i+1]%2==0 && arr[i+2]%2==0) {
console.log("even");
}
if(arr[i]%2!=0 && arr[i+1]%2!=0 && arr[i+2]%2!=0) {
console.log("odd");
}
}
}
oddsAndEvens ([2,4,6]);
You can use Array.prototype.every(). You could also include check if element of array is, for example 7.5
var oddsAndEvens = (arr) => arr.every(n => n % 2 === 0) && "even"
|| arr.every(n => n % 2 != 0) && "odd";
console.log(oddsAndEvens([2, 4, 5])
, oddsAndEvens([33, 99, 7])
, oddsAndEvens([7.5, 4, 6]));
What You need is a counter for odd and event numbers. Below function will count them all and if there are 3 or more matches, then it prints in console log "odd" OR/AND "even". Works for array of any size.
function oddsAndEvens (arr) {
var odd_count = 0,
even_count = 0;
for(i=0; i < arr.length; i++) {
if(arr[i]%2==0) {
event_count ++;
}else if(arr[i]%2!=0){
odd_count ++;
}
}
if(even_count >= 3){
console.log('even');
}
if(odd_count >= 3){
console.log('odd');
}
}
You need to be sure you have 3 defined values first. You need to add:
if(arr[i] && arr[i+1] && arr[i+2]) { }
full code:
function oddsAndEvens (arr) {
for(i=0; i < arr.length; i++) {
if(arr[i] && arr[i+1] && arr[i+2]) {
if(arr[i]%2==0 && arr[i+1]%2==0 && arr[i+2]%2==0) {
console.log("even");
}
if(arr[i]%2!=0 && arr[i+1]%2!=0 && arr[i+2]%2!=0) {
console.log("odd");
}
}
}
}
oddsAndEvens([1,3]); /* nothing. no 3 defined values in a row */
oddsAndEvens([1,3,7]); /* odd */
oddsAndEvens([2,2,8]); /* even */
oddsAndEvens([1,3,1, 9]); /* odd, odd */

Javascript if statement less than 'x' object in array don't show data

Here I am showing related documents. I only want this to show if there is more than one related document in the array.
displayTable = function(data) {
var data = [];
for (var i = 0; i < data.results.data.length; i++) {
if (data.results.data[i].length < 0) {
console.log('dont show');
} else if (data.results.data[i]) {
data.push(data.results.data[i]);
}
}
pubData.results.data[i].length < 0 means less than zero, not less than one.
Use < 1 for less than one:
if (pubData.results.data[i].length < 1)
Or optionally === 0, if it's a true array (the length of a true JavaScript array is never negative):
if (pubData.results.data[i].length === 0)
Or (again for a true array) you can use !:
if (!pubData.results.data[i].length)

Categories

Resources