Loop that will run 20 times for array with two entries - javascript

How can I run a loop 20 times for an array that have only two entries?
I have the following code
const genders = ['male', 'female'];
const randChoice = arr => {
return arr[Math.floor(Math.random() * arr.length)];
};
const loop = () =>
for (let i = ''; i <= 20; i++) {
const data = randChoice(genders);
if(data === 'male') {
const name = randChoice(maleNames);
people.push(new Data(data, name, lastName))
} else {
const name = randChoice(femaleNames);
people.push(new Data(data, name, lastName))
}
console.log('people', people)
return people;
I have tried some different things but never get it working and looping 20 times.
thanksa for all answers.
But let make this more complex
in thisd case. This will not work

The mistake is at Line 8, when you wrote for (let i = ''; i <= 20; i++), you need to first set the variable i to 0, like this: for (let i = 0; i <= 20; i++).
The whole code for your loop will then be:
for (let i = 0; i < 20; i++) {
const data = randChoice(genders);
// here goes if else statement for gender
}
Another mistake that also #Hasan Balcı has pointed out, is that in your code, the loop runs 21 times instead of 20. Why? Because the variable i starts from 0, and the loop runs until it reaches 20, including when its value is 20!
To correct this, instead of writing for (let i = 0; i <= 20; i++), it will have to be for (let i = 0; i < 20; i++), changing i <= 20 to i < 20!
Hope this helped!

Like this you can iterate loop for 20 times:
const loop = () =>{
for (let i = 0; i < 20; i++) {
const data = randChoice(genders);
console.log(data);
}}

Related

for loop only iterates one time

I don't know why this code isn't looping.
It just gives me the first result which is 17°C in 1 day. What about the rest of the values in the array?
const temperatures = [17, 21, 23];
const forcasting = function (arr) {
for (let i = 0; i <= arr.length; i++) {
let forCast = console.log(`${arr[i]}°C in ${i + 1} day.`);
return forCast;
}
};
forcasting(temperatures);
You are returning ‘forecast’ at the first iteration, it will cause the function to end (on any language and not only js), replace the return with print() and see the values.
There are some issues with this code.
1st. It only loops once because you return in the first loop.
return ends the code running inside that function and returns forCast making forcasting equal to the return from the console.log()
just know returning in a loop will end it
2nd. Also for (let i = 0; i <= arr.length; i++) will try to access index 3 when the last index is actually 2. so it should be for (let i = 0; i < arr.length; i++)
you are using return before the loop ends. use this code:
const temperatures = [17, 21, 23];
const forcasting = function (arr) {
let forCast = null;
for (let i = 0; i <= arr.length; i++) {
forCast = console.log(`${arr[i]}°C in ${i + 1} day.`);
}
return forCast;
};
forcasting(temperatures);

Output only one possible result looping thru 2 arrays with if-statement

I have two arrays. Each element of which I compare numbers of first array are greater than the seconds' and if it finds (through if statement) any number from first array greater than any number from second array, I console.log them. However, there might be more than one coincidence but per one request in need to console.log only first result.
Say,
First array has [0.4,0,6]
Second array has [0.5,0.5]
It produces 2 results since there are two matches. How to get only first one.
My code looks like that:
https://jsfiddle.net/oxpwb0j3/2/
const numbers = [0.6,0.4];
for(a = 0; a < numbers.length; a++) {
var res_num1 = numbers[a];
const numbers2 = [0.5,0.5];
for(b = 0; b < numbers2.length; b++) {
var res_num2 = numbers2[b];
if(res_num1 > res_num2){
console.log(res_num1+" = "+res_num2);
}
}
}
it outputs:
0.6 = 0.5
0.6 = 0.5
as I explained in the beginning how to limit to only log the first result like so 0.6 = 0.5.
I'm new to JS and learning. Thank you!
just add break the first time it met the condition.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/break
const numbers = [0.4,0.6];
for(a = 0; a < numbers.length; a++) {
var res_num1 = numbers[a];
const numbers2 = [0.5,0.5];
for(b = 0; b < numbers2.length; b++) {
var res_num2 = numbers2[b];
if(res_num1 > res_num2){
console.log(res_num1+" = "+res_num2);
break;
}
}
}
Try to use labels
const numbers = [0.4,0.5,0.6];
for(a = 0; a < numbers.length; a++) {
var res_num1 = numbers[a];
const numbers2 = [0.5,0.5];
outerloop: for(b = 0; b < numbers2.length; b++) {
var res_num2 = numbers2[b];
if(res_num1 > res_num2){
console.log(res_num1+" = "+res_num2);
break outerloop;
}
}
}

For Loop Scoping with 2D Array

I am working on an Advent Code Challenge and have run into a hall. I solved this error before, but in this instance, I am stuck. The following code is giving me a Uncaught TypeError: Cannot read properties of undefined. in relation to switch (diagArray[i][j]).
My thought is that diagArray is out of scope. Is that true?
Please, any help is great!
const diagArray = [
[0,1,0,0,0,1,1,1,0,0,0,1],
[1,1,0,1,0,0,0,0,0,0,0,1],
[1,1,1,0,0,1,0,0,1,0,1,1]
]; // example data
for(let i = 0; i < diagArray.length; i++) {
for (let j = 0; j < diagArray.length; i++) {
let gammaRate = ''
let epsilonRate = ''
let ones = 0
let zeros = 0
let rates = []
switch (diagArray[i][j]) {
case 1:
ones++
break
case 0:
zeros++
break
default:
break
}
if (ones > zeros) {
gammaRate+=1
epsilonRate+=0
} else {
gammaRate+=0
epsilonRate+=1
}
rates.push([gammaRate, epsilonRate])
// console.log(rates)
}
}
for(let i = 0; i < diagArray.length; i++) {
for (let j = 0; j < diagArray.length; i++) {
This here has multiple problems.
The first for loop is fine, but the second one needs be bounded by the length of the inner array:
diagArray[i].length
And it's also currently incrementing the first loops counts with i++. That needs to be j++
Working example:
const diagArray = [
[0,1,0,0,0,1,1,1,0,0,0,1],
[1,1,0,1,0,0,0,0,0,0,0,1],
[1,1,1,0,0,1,0,0,1,0,1,1]
]; // example data
for (let i = 0; i < diagArray.length; i++) {
for (let j = 0; j < diagArray[i].length; j++) {
let gammaRate = ''
let epsilonRate = ''
let ones = 0
let zeros = 0
let rates = []
switch (diagArray[i][j]) {
case 1:
ones++
break
case 0:
zeros++
break
default:
break
}
if (ones > zeros) {
gammaRate+=1
epsilonRate+=0
} else {
gammaRate+=0
epsilonRate+=1
}
rates.push([gammaRate, epsilonRate])
console.log(rates)
}
}
Also it's usually not advisable to have loops like this for iterating arrays, since, as you've discovered, it's very easy to screw up the indices.
I recommend interating over the values of the arrays instead:
for (const row of diagArray) {
for (const value of row) {
const diagArray = [
[0,1,0,0,0,1,1,1,0,0,0,1],
[1,1,0,1,0,0,0,0,0,0,0,1],
[1,1,1,0,0,1,0,0,1,0,1,1]
]; // example data
for (const row of diagArray) {
for (const value of row) {
let gammaRate = ''
let epsilonRate = ''
let ones = 0
let zeros = 0
let rates = []
switch (value) {
case 1:
ones++
break
case 0:
zeros++
break
default:
break
}
if (ones > zeros) {
gammaRate+=1
epsilonRate+=0
} else {
gammaRate+=0
epsilonRate+=1
}
rates.push([gammaRate, epsilonRate])
console.log(rates)
}
}
Your second iteration was increasing the i variable instead of j while iterating to the length of diagArray instead of diagArray[i].
You can use the Console API to debug your values to find out where the issue originates from without having to guess.
const diagArray = [
[0,1,0,0,0,1,1,1,0,0,0,1],
[1,1,0,1,0,0,0,0,0,0,0,1],
[1,1,1,0,0,1,0,0,1,0,1,1]
]; // example data
for(let i = 0; i < diagArray.length; i++) {
for (let j = 0; j < diagArray[i].length; j++) {
let gammaRate = ''
let epsilonRate = ''
let ones = 0
let zeros = 0
let rates = []
console.log(`${i}:${j} = ${diagArray[i][j]}`)
switch (diagArray[i][j]) {
case 1:
ones++
break
case 0:
zeros++
break
default:
break
}
if (ones > zeros) {
gammaRate+=1
epsilonRate+=0
} else {
gammaRate+=0
epsilonRate+=1
}
rates.push([gammaRate, epsilonRate])
// console.log(rates)
}
}
It's because in the second for loop it says diagArray.length, and it should be diagArray[i].length so that you are getting the length of the second array.
You should update the second for loop expression like this.
for (let j = 0; j < diagArray[i].length; j++) {

How to get next element in for loop in javascript

In a dataset I have different locators. Some places are free (locator = null). I would like to capture these and push them into arrays.
In the subarray may only be locations that are in a row. If a distance is greater than 1 then it comes to the next array.
const freeLocs = locs.filter(elem => !elem.locator)
let temp = []
let array2D = []
for(let i = 0; i < freeLocs.length-1; i++) {
let abs = Math.abs(freeLocs[i+1].position - freeLocs[i].position)
temp.push(freeLocs[i])
if(abs > 1) {
array2D.push(temp)
temp = []
}
}
console.log(array2D)
Now I have the problem that the last array is not filled.
https://jsfiddle.net/5yk0mpt9/2/
Problem starts here:
for(let i = 0; i < freeLocs.length-1; i++) {
with this condition you lose the last item of the array:
i < freeLocs.length-1
it needs to change like this:
i < freeLocs.length
but it also needs an extra check inside the loop before trying to get the
freeLocs[i + 1].position
for the last iteration
for example:
for (let i = 0; i < freeLocs.length; i++) {
temp.push(freeLocs[i]);
if (
(i === freeLocs.length - 1) ||
(Math.abs(freeLocs[i + 1].position - freeLocs[i].position) > 1)
) {
array2D.push(temp)
temp = [];
}
}
working demo here: DEMO

How can I use Javascript to iterate twice over an array element?

Please help! I need to declare an empty array (foodTray = []), and run a loop 5x (for each iteration push a food type), the foodTray has to hold a max of 2 types but the total length should not exceed 5.
const foodTypes = ['seafood', 'nuts', 'seeds'];
I had done this =>
'use strict';
let foodTray = [];
const foodTypes = ['seafood', 'nuts', 'seeds'];
for (let x = 0; x < foodTypes.length; x++) {
const food = foodTypes[x];
foodTray.push(food);
if (foodTray.length < 5) {
foodTray.push(food);
}
}
console.log('I have ' + `${foodTray}.`);
but I was instructed the loop had to run 5 times***** and what I used was the length of the foodTypes.
The desired output should be => I have seafood, seafood, nuts, nuts, seeds.
The problem: I did for (let x = 0; x < *foodTypes.length*; x++)
instead, the loop should run 5 times! I am not sure how I can iterate twice over an element.
Your original code is giving you the desired output which is : I have seafood, seafood, nuts, nuts, seeds.
let foodTray = [];
const foodTypes = ['seafood', 'nuts', 'seeds'];
for (let x = 0; x < foodTypes.length; x++) {
const food = foodTypes[x];
foodTray.push(food);
if (foodTray.length < 5) {
foodTray.push(food);
}
}
console.log('I have ' + `${foodTray}.`);

Categories

Resources