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);
Related
This is my code -
function sortArray(arr) {
let newArray = [];
for (let i = 0; i < arr.length; i++) {
let min = Math.min(...arr);
newArray.push(min);
arr.splice(arr.indexOf(min));
}
return newArray;
}
console.log(sortArray([100, 83, 32, 9, 45, 61]));
and it is giving me this output -
[9, 32];
How is this code actually working? it is looping array.length times, so why is it just pushing only two elements inside the newArray?
Two problems there:
When you use splice() with one argument only, it removes not just the given index, but also everything after that. Add the second argument to remove just one item.
arr.length decreases as you remove elements from it, so you need to store the original value to walk through all the values.
function sortArray(arr) {
let newArray = [];
const length = arr.length;
for (let i = 0; i < length; i++) {
let min = Math.min(...arr);
newArray.push(min);
arr.splice(arr.indexOf(min), 1);
}
return newArray;
}
console.log(sortArray([100, 83, 32, 9, 45, 61]));
The reason for this is that you put arr.length inside the for loop, and loop you splice 1 array value, so the loop run only 2 times.
try add arr.length to const before the for loop and use it instead of arr.length:
function sortArray(arr) {
let newArray = [];
const arrLength = arr.length;
for (let i = 0; i < arrLength; i++) {
let min = Math.min(...arr);
newArray.push(min);
arr.splice(arr.indexOf(min), 1);
}
return newArray;
}
console.log(sortArray([100, 83, 32, 9, 45, 61]));
I have a data like below
data = ["I253,J665,l2575"]
and I need the the results like
I253,
J665,
l2575
when i tried to use for in i am getting like I253,J665,l2575 and I tried for loops also but not getting the result
let data = ["I253,J665,l2575"]
for (let i = 0; i > this.data.length; i++) {
console.log(i)
}
for (let x of this.data) {
console.log(x)
}
tried converting the data in to string and then using split changed into array but then also i am getting typeof object only
below is my stack blitz url =: https://stackblitz.com/edit/angular-ivy-drf1dk?file=src/app/app.component.ts
Modify your data variable like below:
data = ["I253", "J665", "l2575"];
for(let i = 0; i < this.data.length; i++){
console.log(this.data[i]);
}
If you have data variable as data = ["I253,J665,l2575"];
Then split it first and then loop through the generated array:
const arr = data[0].split(',');
for(let i = 0; i < arr.length; i++){
console.log(arr[i] + ',');
}
You were having multiple mistakes. First one was with for condition it should be i < this.data.length not i > this.data.length. Then you need to split and loop over it with for (let j = 0; j < data[i].split(',').length; j++) so data[i].split(',')[j] will return expected value.
In case of 2nd for...of loop you were simply logging whole value. Here also you need to split inside for...of and use one more loop to log.
Alternatively you can also use flatMap and loop over it like for (let m of data.flatMap(x => x.split(','))).
Try it below. You can use this.data, but it won't work in below example so it is used as simply data.
let data = ["I253,J665,l2575"];
console.log("Using for loop");
for (let i = 0; i < data.length; i++) {
for (let j = 0; j < data[i].split(',').length; j++) {
console.log(data[i].split(',')[j]);
}
}
console.log("Using for...of loop");
for (let x of data) {
for (let y of x.split(',')) {
console.log(y);
}
}
console.log("Using flatMap");
for (let m of data.flatMap(x => x.split(','))) {
console.log(m);
}
Two ways to solve this.
Also note that your loop is wrong SHOULD NOT BE '>' and Should Be '<'
1. Your data is at array index zero so if you are to keep the data as is
let data = ["I253,J665,l2575"]
let splits = data[0].split(',')
for (let i = 0; i < splits.length; i++) {
console.log(splits[i])
}
or
let data = ["I253,J665,l2575"]
let splits = data[0].split(',')
for (let element of splits) {
console.log(element )
}
2. Fix the data string
let dataString = "I253,J665,l2575"
let splits = dataString.split(',')
for (let i = 0; i < splits.length; i++) {
console.log(splits[i])
}
or
let dataString = "I253,J665,l2575"
let splits = dataString.split(',')
for (let element of splits) {
console.log(i)
}
Clone of the example provided in question
https://stackblitz.com/edit/angular-ivy-izj7up
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);
}}
I'm trying to return the array an array of numbers that conform to the two if statements. The prompt came from leet code, "Self Dividing Numbers", and asks to take in two arguments, a lower and upper bound and check if whether or not each number in that range is divisible by the digits of each individual number.
When I console.log(num) (the commented out portion, I get a correct list of numbers, but not in an array format. To fix this I thought to add a variable, result and return result after pushing an array to result inside the for loop. However when I do this, i only get the first correct term in an array, but not the full array.
How can this be fixed? I've tried moving the return statement in various locations, but that did not fix the issue.
The function should return [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 15, 22];
function selfDividingNumbers(left, right) {
for (let j = left; j <= right; j++) {
let num = j;
let result = []
let strNum = num.toString();
let dividingDigit = 0;
for (let i = 0; i < strNum.length; i++) {
if (num % parseInt(strNum[i]) == 0) {
dividingDigit++;
}
if (dividingDigit == strNum.length) {
result.push(num)
//console.log(num)
}
}
return result
}
};
console.log(selfDividingNumbers(1, 22));
From your expected output, define result at the very top of the function, and then return only after completely iterating through both loops:
function selfDividingNumbers(left, right) {
let result = []
for (let j = left; j <= right; j++) {
let num = j;
let strNum = num.toString();
let dividingDigit = 0;
for (let i = 0; i < strNum.length; i++) {
if (num % parseInt(strNum[i]) == 0) {
dividingDigit++;
}
if (dividingDigit == strNum.length) {
result.push(num)
//console.log(num)
}
}
}
return result
};
console.log(selfDividingNumbers(1, 22));
To be more concise, you might use .filter check whether .every digit divides evenly:
function selfDividingNumbers(left, right) {
return Array.from(
{ length: right - left },
(_, i) => i + left
)
.filter((num) => {
const digits = String(num).split('');
if (digits.includes(0)) {
return false;
}
return digits.every(digit => num % digit === 0);
});
}
console.log(selfDividingNumbers(1, 22));
When you declare let result = [] inside your for loop you are telling your code to recreate this array every time your loop iterates, thus, removing all previous results pushed into it. Instead, you need to move this outside your for loop to stop this from happening.
Lastly, you need to return only after you're outer for loop is complete, as returning inside your for loop will stop the function from running (and thus stop the loop).
See working example below:
function selfDividingNumbers(left, right) {
let result = [];
for (let j = left; j <= right; j++) {
let num = j;
let strNum = num.toString();
let dividingDigit = 0;
for (let i = 0; i < strNum.length; i++) {
if (num % parseInt(strNum[i]) == 0) {
dividingDigit++;
}
if (dividingDigit == strNum.length) {
result.push(num)
}
}
}
return result
};
console.log(selfDividingNumbers(1, 22));
Can someone please explain to me what I am doing wrong here...
This code is from eloquent javascript and it works fine
function sum(array) {
let total = 0;
for (let value of array) {
total += value;
}
return total;
}
And this is what I wrote for the exercise but returns NaN..
function sum(numArray) {
let add = 0;
for (let a = 0; a <= numArray.length; a++) {
let addIndex = numArray[a];
add += addIndex;
}
return add;
}
Your for loop goes out of array indexes. You have to use:
a < numArray.length
Instead of:
a <= numArray.length
You simply add undefined to add, because you run the index count to long.
for (let a = 0; a <= numArray.length; a++) {
// ^ wrong, takes last index + 1
function sum(numArray) {
let add = 0;
for (let a = 0; a < numArray.length; a++) {
let Addindex = numArray[a];
add += Addindex;
}
return add;
}
console.log(sum([1, 2, 3, 4]));
The issue is because of this a <= numArray.length. Change it to a < numArray.length. This case a[5] that is the 6th element or the element at 5th index is undefined as the array starts from 0 index. So it will add an undefined with previously added number and hence it will be NaN
function sum(numArray) {
let add = 0;
for (let a = 0; a < numArray.length; a++) {
let Addindex = numArray[a];
add += Addindex;
}
return add;
}
console.log(sum([1, 2, 3, 4, 5]))
You're getting an out-of-bounds error. In your for loop, you can change it to:
for (let a = 0; a < numArray.length; a++) {
OR
for (let a = 0; a <= numArray.length - 1; a++) {
The latter works too, but is harder to read.
You can also write a function that has two parameters, an array and a callback function that adds the values of the array like
function forEach(array, arrayAdder){
for (var i = 0; i < array.length; i ++)
arrayAdder(array[i]) ;
}
We can now initialize both the array and the sum like
var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], sum = 0;
After that we pass it into the function like this
forEach(array, function(number){
sum += number ;
});
Then print the answer
console.log(sum);