pushing data into array inside a for loop JavaScript - javascript

Could someone give me an explanation as to why this works
itemIds = [];
for (var i = 0; i <= data.length; i++) {
itemIds.push(data[0].item);
}
console.log(itemIds); // outputs as expected, the same thing, data.length times
But this does not work (the only change is adding i into the push())
itemIds = [];
for (var i = 0; i <= data.length; i++) {
itemIds.push(data[i].item);
}
console.log(itemIds); // TypeError: Cannot read property 'item' of undefined
I need to do this as data in this example is coming from an angular $http call, and returning an object. I don't understand why statically putting in 0 works, but trying to make it iterate through each data.item does not.

This is because your variable i will eventually increment above the length of the array.
You need to change your for loop from i <= data.length to i < data.length.
This will ensure that the i variable will always be within the bounds of the array.
Considering that the index is zero-based, but the length will count up from one, the length will always be one more than the highest index.

Here is my dummy explanation.
i can never be equal to data.lenght
If for example:
var data = ['Bob', 'John', 'Mike'];
data[0] = Bob
data[1] = John
data[2] = Mike
data[3] = ?
Therefore data[3] cannot be equal to data.length = 3, it starts looping through 0.
Hope it helps for newbies.

Just to demostrate what goes wrong
basket = ['milk', 'egg', 'chees']
for (var i = 0; i <= basket.length; i++) {
console.log('loop ' + i, basket[i])
}
/*
Logs:
loop 0 milk
loop 1 egg
loop 2 chees
loop 3 undefined
*/

Change
for (var i = 0; i <= data.length; i++)
to
for (var i = 0; i < data.length; i++)

basket = ['milk', 'egg', 'chees']
var x = "";
for (var i = 0; i <= basket.length; i++) {
x = 'loop ' + i, basket[i];
console.log(x);
}
Hope it solves the problem. 'loop ' + i, basket[i]; -- itself creates an empty unidentified element if is not declared with a variable and variable must have an empty content, like this var x = "";

Related

Sum of array elements in JavaScript

I'm trying to solve this problem where I initialize an array of 5 elements and print the sum of the elements. I can't wrap my head around the logic behind the solution. Please review my code.
Another problem with reading an array of 5 integers and printing the smallest element. I keep getting the wrong answer...
This's a script embedded inside an HTML file.
Problem 1
var num= [1,1,1,1];
var total=num[0];
for( var i=0 ; i < num.length ; i++)
{
total =+num[i];
}
window.alert("The total is "+ total);
I expected the answer to be 4, but all I get is 1.
Problem 2
var r = new Array(5);
var len = r.length;
for(var i=0 ; i <len ; i++)
{
r[i] = window.prompt("Enter the elements of the array");
}
var small= [0];
for(var j=0; j< len ; j++)
{
if(r[i] < small )
small = r[i];
}
window.alert("The smallest element is the array is "+small);
I get the last element in my array as the smallest element which's obviously isn't right.
In problem 1) you just need to change =+ to +=
In problem 2) you need to start in the first element of r and in the for loop you need index the r array by the variable j instead of i variable
var r = new Array(5);
var len = r.length;
for(var i=0 ; i <len ; i++)
{
r[i] = window.prompt("Enter the elements of the array");
}
var small = r[0];
for( var j=0; j< len ; j++)
{
if(r[j] < small )
small = r[j];
}
window.alert("The smallest element is the array is "+small);
But you could just do:
const min = Math.min(...r)
window.alert("The smallest element is the array is "+ min);
There are a couple things here.
For problem 1:
Since you initialize the total to the first item I think you end up counting it 2 times. Likely you'd want to initialize to 0. var total = 0.
You will also want to use += instead of =+ the latter sets the value instead of adding it.
For Problem 2:
new Array(5) creates a new sparse array. It's kinda weird. It's like it's full of undefined values. So when you assign small you'll want to access the first element of r, var small = r[0] but that will be undefined due to r being a sparse array. So you'll want var r = new Array(5).fill().map((x,i) => i) to set values in that array. You will also want to use j instead of i in the body of the second loop.
That should do it ;).
Hi The problem 1 could be tackled with reduce method check the Docs here:
The problem 2 could be solved with Math.min method:
var num= [1,1,1,1];
var numMin= [100,1121,1212,122, 12];
//Problem1
let totalSum = num.reduce( ( accumulator, currentItem ) => {
return accumulator = accumulator += currentItem;
} , 0 );
console.log(totalSum)
//Problem 2
console.log( 'Min',Math.min( ...numMin ) );
Here is a replit so you can play with the code
// Find array elements sum
let total = 0;
let arr = [1,2,3,4];
arr.map(el => total+=el);
console.log(total); // 10
// Find array smallest element
let arr = [1,-2,13,-4,7];
let smlEl = arr[0]
arr.map(el => {
if(el < smlEl) {
smlEl = el;
}
})
console.log(smlEl); // -4

Understanding a JavaScript For Loop

If I have variables and a for loop with a condition set-up like this:
var scores = [23, 53, 85];
var arrayLength = scores.length;
var i;
for(i = 0; i < arrayLength; i++)
Does the i refer to the scores array indexed position of 0, or is i just the counter number, which is set to 0?
I'm kinda confused on understanding what's happening.
Any help is appreciated!
Here you can see it in action:
var scores = [23, 53, 85];
var arrayLength = scores.length;
var i;
for(i = 0; i < arrayLength; i++) {
console.log('i = ' + i + ', scores[i] = ' + scores[i]);
}
console.log('End of for loop: i = ' + i);
One important thing to understand is that i will be incremented until the condition i < arrayLength is not met anymore. So it will reach the value 3 but the for loop will end immediately. Therefore, the code inside the loop is not executed for i = 3.
i is just a counter number which is initially set to 0 and increments up to arrayLength (3 in this case)
i just refers to a number that (in this case) counts up from 0 until arrayLength. You have to explicitly access the values in the array at each i by using scores[i], after which you can modify/use the value in any way you see fit.
i is the counter number.
A for loop works like so:
For each value of array length, use i as a counter variable
each time through the loop increment the variable of i when you are done (i++)
you could expand it like so...
for(i = 0; i < arrayLength; i++)
{
console.log('position ' + i + ' is ' + scores[i]);
}//now that I am done, increment i and go through again until i is no longer less than array length
Right so you have the set the i as a variable by initially going
var i;
Within the for statement you have set the i variable to 0.
for(i = 0; i < arrayLength; i++){
}
Then the for statement is saying if i is less than the array length run the for statement. Each time the for statement runs you are adding 1 to i because of i++;
Every time the for statement will check to see if i is less than the arrayLength if it isnt it will exit out of the for.
So for this instance the for each would run 3 times because the array length is 3.
Make sure you have open and closing brackets on the for statement
So your for statement should look like this.
for(i = 0; i < arrayLength; i++){
}

Why do I get "Uncaught TypeError: Cannot read property 'length' of undefined(…)"?

Error Message: Uncaught TypeError: Cannot read property 'length' of undefined(…)
Line 44, Column 23
I have read every post I can find related to this error but have not found anything applicable to this situation.
I'm trying to take a string and turn it into an array of arrays that is formatted to take the shape of steps (codewars' kata); one word across, next word down and so on. The problem I'm running into is that I keep getting an Uncaught TypeError: Cannot read property 'length' of undefined(…) when trying to use the length of an array element within a for loop. So in this nested loop:
for(var i = 0; i < masterStringOdd.length; i++){
temp2 = proArr.slice(0);
start2 = even[i].length - 1;
for(let j = 0; j < odd[i].length; j++){
let replace2 = masterStringOdd.charAt(i);
Array.prototype.splice.apply(temp2, [start2, 1].concat(replace2));
finalOdd.push(temp2);
}
start2 += even[i+1].length - 1;
}
With the last line "start2 += even[i+1].length - 1;" (I have tried about a thousand different various of this) I get the error, but if I return that line "return even[i+1].length - 1;" I get 5, which is the correct length. My complete code is at the end of this email if anyone wants to look at it, and believe me I understand it is ridiculous and awkward (working code and completely unpolished) - skills at hand and all that.
Just can't figure out why I can't get and use the value of the element's length in this case. Any help would be greatly, greatly appreciated.
function wordStep(str) {
let array = str.split(" ");
let even = [], odd = [], proArr = [], finalEven = [], finalOdd = [];
//for loop to create sperate arrays for across and down
for (let i = 0; i < array.length; i++){
if (i%2 === 0){
even.push(array[i]);
} else {
odd.push(array[i].slice(1,-1));
}
}
//data collection and tool variables, might delete them if the are not needed
let finalLength = even.join("").toString().length - (even.length - 1);
let masterStringEven = even.join("").toString();
let yAxis = odd.join("").toString().length;
let masterStringOdd = odd.join("").toString();
//for loop to create protype array
for (let i = 0; i < finalLength; i++){
proArr.push(",");
}
// for loop to create final evens arrays
let start = 0;
for(let i = 0; i < even.length; i++){
let temp1 = proArr.slice(0);
let replace = even[i].split("");
Array.prototype.splice.apply(temp1, [start, replace.length].concat(replace));
finalEven.push(temp1);
start += replace.length-1;;
}
// nested loops for final odds' array
let temp2 = []
let start2 = 0;
for(var i = 0; i < masterStringOdd.length; i++){
temp2 = proArr.slice(0);
start2 = even[i].length - 1;
for(let j = 0; j < odd[i].length; j++){
let replace2 = masterStringOdd.charAt(i);
Array.prototype.splice.apply(temp2, [start2, 1].concat(replace2));
finalOdd.push(temp2);
}
start2 += even[i+1].length - 1;
}
}
Fundamentally, what's happening is that you're going past the end of the even array, so even[i] gives you undefined, and then you try to read the length of undefined, which causes the error.
And indeed, we can see that in this loop:
for(var i = 0; i < masterStringOdd.length; i++){
temp2 = proArr.slice(0);
start2 = even[i].length - 1;
for(let j = 0; j < odd[i].length; j++){
let replace2 = masterStringOdd.charAt(i);
Array.prototype.splice.apply(temp2, [start2, 1].concat(replace2));
finalOdd.push(temp2);
}
start2 += even[i+1].length - 1;
}
...you're assuming that masterStringOdd.length will always be less than even.length. Nothing in the code ensures this, and in fact it will frequently not be true. masterStringOdd.length is the length of the odd array's entries joined together as a string; even.length is the number of even entries. So there are two reasons why even.length may not be at least as big as masterStringOdd.length: 1. The latter is the length of a string, not an array; and 2. The latter relates to odd, not even.
The issue with your code is that you are not checking the even and odd arrays length before accessing them. This will create issue if you have str value in wordStep(str) which do not push values in these array at the indices where you are accessing those.
Put proper array length check for accessing the array at the particular index.
for(var i = 0; i < masterStringOdd.length; i++){
temp2 = proArr.slice(0);
if(even.legth > i)
start2 = even[i].length - 1;
if(odd.length > i){
for(let j = 0; j < odd[i].length; j++){
let replace2 = masterStringOdd.charAt(i);
Array.prototype.splice.apply(temp2, [start2, 1].concat(replace2));
finalOdd.push(temp2);
}
}
if(even.length > i +1)
{
console.log(even.length);
start2 += even[i+1].length - 1;
}
}
for example wordStep("Life is good for us"); this call will fill the array properly and you will not get any error.
but if its wordStep("Life Good");, you will see the issue in your code if proper length check are not applied
plunker to verify : http://plnkr.co/edit/QQovAAzlDhXgucikCGAb?p=preview

I Want To Print 1 to 100 Numbers Using Arrays In Javascript Only

<!DOCTYPE html>
<html>
<head>
<title>100-Numbers</title>
</head>
<body>
<script>
var points = new Array(100);
var label = points.length;
for (var i = 0; i < label; i++) {
console.log(points[i]);
}
</script>
</body>
</html>
This is my First question in Stackoverflow. As i am an beginner, Please bare me and i need alot of support from you people. I m trying to print 1 to 100 numbers using arrays in javascript only. I'm Facing some errors in the above code. Please correct my mistakes to get the output..Thankyou in advance.
This will print 1-100 without any loops
Array.from({length: 100},(_,x) => console.log(x+1))
he said he wants to print 1-100 from an ARRAY...So the array needs to be populated, first. THEN, you can loop through the array.
var points = new Array(100);
for (var i = 0; i < 100; i++) {
points[i] = i + 1; //This populates the array. +1 is necessary because arrays are 0 index based and you want to store 1-100 in it, NOT 0-99.
}
for (var i = 0; i < points.length; i++) {
console.log(points[i]); //This prints the values that you stored in the array
}
The array values are uninitialized. I'm assuming that you want to print the values 1 to 100 using arrays where the values 1 to 100 are inside the array.
First initialize the array.
var oneToHundredArray = [];
Now populate it with values 1 to 100.
for(var value = 1; value <= 100; value++) {
oneToHundredArray.push(value);
}
Now the contains the values you want. Just loop and print over it now.
for(var index = 0; index < oneToHundredArray.length; index++) {
console.log(oneToHundredArray[index]);
}
Done :)
Array.from(Array(100), (_,i) => console.log(i+1));
The second parameter acts as mapping callback, so you also do this...
const arr = Array.from(Array(100), (_,i) => i+1);
for(num of arr) {
console.log(num);
}
Reference: Array.from
You should start off with an empty array, then run a loop for 1-101, I logged the iterator so you can see the values populate, you then need a binding agent to hold the value of the iteration, then you would need to push those values to your empty array.
var numbersArray = [];
for( var i = 1; i <101; i++){
console.log(i);
var numbers = i;
numbersArray.push(numbers);
}
After that, you then need to run a loop for the length of the numbersArray to output the individual results.
for(var m=0; m<= numbersArray.length -1; m++){
console.log(numbersArray[m]);
}
output console.log logs numbers 1-100 respectively.
var label = new Array(100);
for (var i = 0; i < 100; i++) {
label[i] = i + 1;
}
for (var i = 0; i < label.length; i++) {
console.log(label[i]);
}
It's much more easier with "while"
var i = 1;
while (i < 100) {
document.write(i + "<br/>");
i++;
}
Using a for loop:
function get_array() {
var arr = [];
for(var i=1; i<=100; i++) {
arr.push(i);
}
console.log(arr);
}
get_array()

Why is this incrementer returning NAN when if I hard code the index it works as expected?

I am trying to do a simple factorial code challenge, but with Javascript, when I try to get the index position by looping of the indexes, I get NAN. I understand that NAN is of the typeOf number, just that Javascript doesn't know which number. I don't see why that is happening in this case. Also how can I use get the index of an array by looping over them in Javascript? Thanks!
// Input = 4 Output = 24
// Input = 8 Output = 40320
var total = 0;
var factor_Array = [];
function FirstFactorial(num) {
for (var i = 1; i <= num; i++){
factor_Array.unshift(i);
// console.log(factor_Array);
}
for (var j = 0; j < factor_Array.length; j++){
// Why does this work??? But not when I use 'j' to grab the index position? Seems like BOTH ways should work
total = factor_Array[0] * factor_Array[0+1];
total = factor_Array[j] * factor_Array[j+1];
}
console.log(total);
//return num;
}
FirstFactorial(4);
Because when j = (factor_Array.length-1) it tries to access the j+1 element, which doesn't exist.
The following would work as you expect
for (var j = 0; j < (factor_Array.length-1); j++){
total = factor_Array[j] * factor_Array[j+1];
}
When you loop
for (var j = 0; j < factor_Array.length; j++){
total = factor_Array[j] * factor_Array[j+1];
}
Then then on the last iteration you will be out of the array bounds since
j = factor_Array.length - 1
and you're accessing j + 1.

Categories