I found myself a problem. I want to print an array from number 0 to 100. if the number is divisible by 3, I want to print flip. if the number is divisible by 5, I want to print flop. for example the array should be [0,1,2,'flip',4,'flop','flip,........,'flop']. How to do this in JS? So far I have done this but it doesn't print the whole array.
function wow() {
var arr = []
for (let i = 0; i <= 100; i++) {
if(i!=0){
if(i%3===0){
i='flip'
arr.push(i)
}
if(i%5===0){
i='flop'
arr.push(i)
}
}
arr.push(i)
}
console.log(arr)
}
wow()
You're changing the variable i within the for loop which you shouldn't be doing. Try using a temp variable for determining what gets pushed to your array.
Also, if a number is divisible by 3 AND 5 then the latter (flop) takes precedent, is that what you expect to happen?
function wow() {
var arr = []
for (let i = 0; i <= 100; i++) {
let temp = i;
if (i != 0) {
if (i % 3 === 0) {
temp = 'flip'
}
if (i % 5 === 0) {
temp = 'flop'
}
}
arr.push(temp)
}
console.log(arr);
}
Here's a bit shorter version...
let arr = Array.from({
length: 101
}, (e, i) => i)
arr.forEach((n, i) => {
Number.isInteger(n / 3) ? arr[i] = 'flip' : null, Number.isInteger(n / 5) ? arr[i] = 'flop' : null
})
console.log(arr)
const dot = (a,b) => x => a(b(x));
const id = x => x;
function flipflop(n){
const f = (N, m) => n % N ? id : x => _ => m + x('');
return dot(f(3, 'flip'), f(5, 'flop')) (id) (n);
}
let arr = Array(101).fill(0).map((_,i)=>flipflop(i));
console.log(arr);