I'm required to loop through an array using the .forEach method, returning all the values and if any of the numbers are a multiple of 3 or 5 and then also both 3 & 5, that number must be returned as a string. My code thus far:
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 issue I'm having is that I'm unable to get it to return the final string of "FizzBuzz" & also omit the initialization of the count variable from displaying in the console.
I'm a total beginner with JS so if you could provide an explanation of the answer where applicable I will appreciate it.
Images of outputs below:
Edit:
I forgot to mention that it's an exercise which is part of an assignment so I'm required to use the forEach method, which also makes it different to the other other question linked to, in that a for loop was used there.
CodePudding user response:
I used guard clauses to make the whole if statement stuff a little more clean
you can use Array.forEach() with the index as argument, which is quite helpful here
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)
also be aware, that javascript arrays start with the index 0 ... so count[item] = [item]
leaves an undefined spot at count[0] ... you should rather have your forEach function make use of the index argument, that can be passed to it (in your particular case using count[item] = [item] doesn't create that many problems) but better do it the right way from the start
here the code 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"
}
})
CodePudding user response:
You needed to check "FizBuzz" first and then "Fizz" and "Buzz" seperately. In this case I would prefer to use .map instead of .forEach in this case, because .map returns each element, so you don't 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)