This question already has answers here:
Loop (for each) over an array in JavaScript
(40 answers)
Closed 7 years ago.
For me this looks odd:
products = ["Item1", "Item2", "Item3"];
for (var x in products) {
debugger;
console.log(x);
// x === "0" instead of "Item1"
}
I wonder why?
for..in loops over enumerable properties and arrays have numerical properties which acts as index. It is to be used with only objects.
Doing so with Arrays will also give you properties which you won't be interested in(such as those properties which are on the higher chain of prototypic inheritance from Object object)
So use a simple for loop or Array.forEach
products.forEach(function(str){
console.log(str);
});
// or
for(var i = 0; i < products.length; i++)
console.log(products[i]);
That's because in your case, variable x is holding the array item's index, and not the value. Instead of x, you should use products[x].
products = ["Item1", "Item2", "Item3"];
for (var x in products) {
debugger;
console.log(products[x]);
}
Now, instead of:
0
1
2
you'll get
Item1
Item2
Item3
Iterate over the array like this.
U use var in arr if you want to iterate over properties of an object, not an array!
var products = ["Item1", "Item2", "Item3"];
for (var i =0; i< products.length;i++) {
debugger;
console.log(products[i]);
// x === "0" instead of "Item1"
}
Related
This question already has answers here:
Get column from a two dimensional array
(11 answers)
Closed last month.
I have a function that accepts an array of arrays as an argument and i need to get access to a specific element of the inner array to push it to a locally scoped empty array, so that i can use reduce method to return a net total.
I can get access using the map method of the specific element in the inner array and push these elements to an array but i can not seem to achieve this using a standard for loop.
// here is the array and i require access to the totals
var finances = [
["Jan-2010", 884],
["Feb-2010", 655],
["Mar-2010", 1013],
["Apr-2010", 417],
["May-2010", -7503],
["Jun-2010", 857],
["Jul-2010", 3096],
["Aug-2010", 885],
["Sep-2010", -6386],
["Oct-2010", 532],
["Nov-2010", 3810],
];
function netTotal(financeArray) {
// lets create a variable here to return the net total to the function
let net;
// lets create an empty array here to store all the totals to use with reduce method
let totals = [];
// we need to loop through the array and push element to the totals array
for (let i = 0; i < financeArray.length; i++) {
let innerArrayLength = financeArray[i].length;
for (let j = 0; j < innerArrayLength; j++) {
totals.push(financeArray[i][j]);
}
}
// lets use the reduce method to return the net total
// return (net = totals.reduce((prev, next) => prev + next));
// returning the totals array to check what is pushed to this array
return totals;
}
console.log(netTotal(finances));
// output to console
Array(22) [ "Jan-2010", 884, "Feb-2010", 655, "Mar-2010", 1013, "Apr-2010", 417, "May-2010", -7503, … ]
The totals array should be a flat array with all the amounts as elements so reduce can work to total every amount instead running the above function i get 22 elements in a single array because the original array is 11 arrays within the outer array.
How can i use the for loop to get access to only the amounts and push each element to this new empty array.
Any help much appreciated..
Your nested for loops cause all elements of the arrays to be pushed. Replace them with:
for (let i = 0; i < financeArray.length; i++) {
let innerArray = financeArray[i];
let amount = innerArray[1];
totals.push(amount);
}
Setting amount = innerArray[1] ensures you only grab the amounts and not unnecessary elements.
You can use flatMap method.
totals = financeArray.flatMap(f => f[1]);
const total = totals.reduce((prev, curr) => prev + curr, 0);
MDN: flatMap()
This question already has answers here:
Swap rows with columns (transposition) of a matrix in javascript [duplicate]
(5 answers)
Closed 7 years ago.
This question was incredibly hard for me to summarize in the title, so I'm sorry if it is misleading.
I have an array of arrays formatted like so:
array = [ [1,2,3,4,5,6,7,8,9],
[2,3,4,5,6,7,8,9,1],
[3,4,5,6,7,8,9,1,2],
[1,2,3,4,5,6,7,8,9],
[2,3,4,5,6,7,8,9,1],
[3,4,5,6,7,8,9,1,2],
[1,2,3,4,5,6,7,8,9],
[2,3,4,5,6,7,8,9,1],
[3,4,5,6,7,8,9,1,2]]
As you can see it's essentially a table with the subarrays as the rows in the table.
I want to create a function that takes the main array and essentially rotates it 90degrees clockwise. So the new subarrays are the first index of each array, the second index of each array, 3rd index of each array etc...
( I want my new main array to contain arrays of each column in this data set).
Thank you!
I have used temporary array newArray which will hold the resultant multidimensional array. (Assumption: as shown in question example, main array size and content-arrays' size should be same).
var newArray = [];
for(var i = 0; i < array.length; i++) {
for(var j= 0; j < array.length; j++) {
newArray[j] = newArray[j] || [];
newArray[j][i] = array[i][j];
}
}
console.log(newArray);
This question already has answers here:
Combining two arrays to form a javascript object
(11 answers)
Closed 7 years ago.
How i get below output in javascript
var keys = ["1","2","3"];
var values = ["one", "two","three"];
var final = {
"1": "one",
"2": "two",
"3": "three"
}
Loop over one of the arrays and use the index to access the other, save in an object
var result = {};
keys.forEach(function(item, index) {
result[item] = values[index];
});
A very simple loop should suffice, copying the values & keys at each index into a new object:
var finalOutput = {};
for(var i=0, j=keys.length; i<j; i++) {
finalOutput[keys[i]] = values[i];
}
Working Example
Note: You shouldn't use final as a variable name as it is a reserved future keyword
I have the following JavaScript code fragment
var ip = new Array();
// This array filled with values and passed to function
function calculateTime(ip) {
for (i in ip) {
window.alert(i);
if (!i in myArray) {
myArray[i] = 0;
} else {
myArray[i] += 1;
}
}
}
I expect i to be an index (0, 1, 2 ...) but sometimes window.alert prints "arrayIndex" and because of that my code doesn't work correctly. Can someone explain me the reason? I am new in JavaScript.
for in will loop over all the enumerable properties of an object.
None of the properties that come with an array are enumerable in modern browsers, but any that are added (such as the normal array indexes or any custom named properties) will be.
Somewhere you have some code that is adding an arrayIndex property to your array and it is coming up when you loop over it.
var myArray = [];
myArray[0] = 1;
myArray[1] = 1;
myArray[2] = 1;
myArray.arrayIndex = 1;
for (prop in myArray) {
console.log(prop);
}
If you only want to get numerical indexes, then use a standard for loop.
for (var i = 0 ; i < myArray.length ; i++) {
console.log(i);
}
For arrays, you should use a numeric variable rather than in:
for(var i = 0; i < ip.length; i++)
in is to iterate over the keys of an Object, but even there you have to take much care to filter out inherited properties.
Now, since arrays are objects too in JavaScript, you can assign them object properties:
ip["arrayIndex"] = 'some value';
Then "arrayIndex" will show up in a for...in iteration, whereas in a "normal" for loop, it won't.
Use either
for(var i=0; i<ip.length; i++){
//your code
}
or
ip.forEach(function(val,i){
// your code
});
The for(var x in y) loop works best for Object rather than Array. When you use it on arrays it will loop through all properties including named ones like length not just numerical indices.
This question already has answers here:
Loop (for each) over an array in JavaScript
(40 answers)
Closed 8 years ago.
Okay, take it easy on me. I am really new to JavaScript and having issues getting the for-each loop to work correctly. Any Tips?
var array = ["Bob", "Nancy", "Jessie", "Frank"];
var arrayLength = myStringArray.length;
for (var i = 0; i < arrayLength; i++) {
document.write(array);
}
var myArray = ["Bob", "Nancy", "Jessie", "Frank"];
var arrayLength = myStringArray.length;
for (var i = 0; i < arrayLength; i++) {
//Do something with element myArray[i]
}
I guess you need something like this.
Edit: Your array has only 4 elements. In the 2nd line I save the length of your array (4 elements --> length is 4) in the variable 'arrayLength'. Then I wrote a simple for-loop which cycles the 'i' from 0 till 3 so you can access your elements from your array as 'myArray[i]'.
The for in is used to iterate over properties on the object. It is not the same as a regular foreach. Use a for loop for this