How to push items into a dynamically created array - javascript

So I'm just beginning to code and have learnt only basic codes and I have created arrays dynamically with:
for (var j=0; j<20; j++) {
this["row"+j] = [];
for (var i=0; i<10; i++) {
["row"+j].push("false");
}
}
but now I want to make it so that I can push items into the previously created row1[], row2[], etc... so that it could be like row1[false, false...] and row2[false, false...] Is there a way to do that?

It is not clear what this is referring here. Rather I will suggest to create an object and in that object keys will be ["row" + j], the value of which will be an [] and then inside the nested loop push value to that array
let obj = {};
for (var j = 0; j < 20; j++) {
obj["row" + j] = [];
for (var i = 0; i < 10; i++) {
obj["row" + j].push("false");
}
}
console.log(obj)

If you want to create arrays not inside object but like normal arrays you can use window and then variable name to create variable.
Normally when you declared varibale in will be inside window object(you can access it without writing window.{variable name}). So you can take advantage of window to created dynamic variable.
for (var j = 0; j < 20; j++) {
window["row" + j] = []; //<-----use window to create dynamic array
for (var i = 0; i < 10; i++) {
window["row" + j].push("false");
}
}
row1[0] = "true"; // editing content of array
console.log(row1,row2);
In the above we have created 20 variable name row0,row1,.... and you can directly access it like normal arrays.

Related

Shift() elements from an array and push() into another

I'm trying to do something like drawing cards.
I have an array with 52 elements (deck[]), and I want to remove the first 13 elements and put them into another array, lets say player1[].
Then remove the next 13 elements and put them into player2[]...and so on.
I did this:
var deck = [], player1 = [], player2 = [], player3 = [], player4 = [];
function distributeCards(){
for(var i = 1; i < 5; i++){
for(var j = 0; j < 13; j++){
player+i.push(deck.shift(j));
}
}
}
The array variables are declared outside, because I have to access them in other functions.
It says player is not defined...how should I write this?
You can't make up variable name with that. Instead, you should consider using array to store player's card, so you can dynamically reference each of the player's deck like this:
var deck = [];
var numOfPlayers = 4;
var players = new Array(numOfPlayers);
function distributeCards(){
for(var i = 0; i < numOfPlayers; i++){
players[i] = [];
for(var j = 0; j < 13; j++){
players[i].push(deck.shift(j));
}
}
}

Nested array for loop

I'm stuck trying to figure out how to loop trough nested arrays.
I have an array called worldShapes that contains child arrays. I want to loop trough the parent array and get all the child arrays from it.
Here's my attempt:
//Nested array
worldShapes = [
[33,108,66,141,99,174,99,207,132,207,165,207,165,240],
[132,306,165,306,165,339,165,372,132,405,99,405,99,438,132,438,165,438],
[198,339,231,339,264,372,297,372,330,405,363,438,396,438],
[198,174,198,273,231,306,264,306],
[231,174,231,240,264,273,297,273],
[396,306,462,306,495,339,495,372,528,405,528,438,561,438,594,471],
[660,504,561,504,495,504]
];
//trying to loop trough each item in the child array
(function(){
var wShapes = worldShapes; //create a local variable
var wLen = wShapes.length; //store the length as a variable
for (var i = 0; i < wLen; i++) {
for (var j = 0; j < wShapes[i].length; j++){
console.log(wShapes[i][j]); //this is propably wrong, trying to access the current child item of the current parent array
}
}
})
Just add (); to the very end of your code ;-)
You've simply forgotten to invoke your anonymous function
To execute the function, add ()
(function () {
var wShapes = worldShapes; //create a local variable
var wLen = wShapes.length; //store the length as a variable
for (var i = 0; i < wLen; i++) {
for (var j = 0; j < wShapes[i].length; j++) {
console.log(wShapes[i][j]); //this is propably wrong, trying to access the current child item of the current parent array
}
}
}()); // here
Fiddle

Pushing value into a multidimensional array

I have surfed the problem but couldn't get any possible solution ..
Let's say i have a var like this
var data = [
{
'a':10,
'b':20,
'c':30
},
{
'a':1,
'b':2,
'c':3
},
{
'a':100,
'b':200,
'c':300
}];
Now , i need a multidimensional array like
var values = [[10,1,100], //a
[20,2,200], //b
[30,3,300]]; //c
What i have tried is
var values = [];
for(var key in data[0])
{
values.push([]); // this creates a multidimesional array for each key
for(var i=0;i<data.length;i++)
{
// how to push data[i][key] in the multi dimensional array
}
}
Note : data.length and number of keys keeps changing and i just want to be done using push() without any extra variables. Even i don't want to use extra for loops
If you guys found any duplicate here , just put the link as comment without downvote
Try this:
var result = new Array();
for(var i = 0; i < data.length; i++) {
var arr = new Array();
for(var key in data[i]) {
arr.push(data[i][key]);
}
result.push(arr);
}
also if you don't want the 'arr' variable just write directly to the result, but in my opinion code above is much more understandable:
for(var i = 0; i < data.length; i++) {
result.push(new Array());
for(var key in data[i]) {
result[i].push(data[i][key]);
}
}
Ok, based on your comment I have modified the the loop. Please check the solution and mark question as answered if it is what you need. Personally I don't understand why you prefer messy and hard to understand code instead of using additional variables, but that's totally different topic.
for(var i = 0; i < data.length; i++) {
for(var j = 0; j < Object.keys(data[0]).length; j++) {
result[j] = result[j] || new Array();
console.log('result[' + j + '][' + i + ']' + ' = ' + data[i][Object.keys(data[i])[j]])
result[j][i] = data[i][Object.keys(data[i])[j]];
}
}

How to loop through Nested Json Array with (JavaScript) for loop and display the text

This may be a fairly simple question but it's just not working for me no matter how many times I change the for loop around. So how would you loop through this array using a for loop in JavaScript?
var fielditems =[
[["News Tips"],["Opinions"],["MedMinutes"]],
[["Yes"],["No"],["Maybe"]],
[["How"],["Why"],["When"]]
];
This is what I have and it's not working. I used an alert to just test out the result but it's not even returning anything.
for(itemSet in fielditems){
var itemSetValues = fielditems[itemSet];
for(set in itemSetValues){
var itemValue = itemSetValues[set];
for(value in itemvalue){
alert(itemValue[value]);
}
}
}
What am I doing wrong?
Don't use for() with in for arrays. It's for object properties. Use the standard format instead.
Demo: http://jsfiddle.net/ThinkingStiff/EVWch/
Script:
var fielditems =[
[["News Tips"],["Opinions"],["MedMinutes"]],
[["Yes"],["No"],["Maybe"]],
[["How"],["Why"],["When"]]
];
for( var itemIndex = 0; itemIndex < fielditems.length; itemIndex++ ){
var itemSetValues = fielditems[itemIndex];
for(var setIndex = 0; setIndex < itemSetValues.length; setIndex++ ){
var itemValue = itemSetValues[setIndex];
for(var valueIndex = 0; valueIndex < itemValue.length; valueIndex++ ){
alert(itemValue[valueIndex]);
};
};
};
​
Firstly, console is your friend. You get error ReferenceError: itemvalue is not defined because javascript is case sensitive. Change itemvalue in the most nested loop to itemValue.
Secondly, if you want iterate thorugh an array, you should use for-loop instead for-in-loop
Don't use for-in loops on arrays
Don't use (running) variables without declaring them as local
for (var i=0; i<fielditems.length; i++) {
var itemSetValues = fielditems[i];
for (var j=0; j<itemSetValues.length; j++) {
var itemvalue = itemSetValues[j]; // notice the case
for (var k=0; k<itemvalue.length; k++) {
alert(itemvalue[k]);
}
}
}
for..in is for objects ({}), not for arrays ([]).
You need to use a standard for loop.
for(var i = 0, iLen = fielditems.length; i < iLen; i++){
var iItem = fielditems[i];
for(var j = 0, jLen = iItem.length; j < jLen; j++){
var jItem = iItem[j];
alert(jItem[0]); // you can also add another loop here, if this will have more elements
}
}
NOTE:
for(var i = 0, iLen = fielditems.length; i < iLen; i++)
is better than:
for(var i = 0; i < fielditems.length; i++)
because fielditems.length isn't requested each loop, just once at the start.

Using .set on a filtered array of IDs in backbone

I used Underscore.js's _.filter to get an array of object ids like so:
var downstreamMeters = _.filter(that.collection.models, function(item) { return item.get("isdownstreammeter"); });
Now I want to set a certain attribute of each model in the array. I thought it would make sense to do this:
for (var i = 0; i < downstreamMeters.length; i++) {
var sum = 0;
inputMeters = downstreamMeters[i].get("inputmeters");
for (var i = 0; i < inputMeters.length; i++) {
var flow = parseFloat(that.collection.get(inputMeters[i]).get("adjustedflow"));
sum += flow;
}
downstreamMeters[i].set({incrementalflow: sum});
}
However, I get the error:
Uncaught TypeError: Cannot call method 'set' of undefined
I checked the downstreamMeters array and it has the right objects in it. What do I need to do to set the attribute for each model in the array?
Saying for(var i = 0; ...) is somewhat misleading. JavaScript hoists all var declarations up to the top of the closest scope and for loop doesn't create its own scope. The result is that this:
for (var i = 0; i < downstreamMeters.length; i++) {
var sum = 0;
inputMeters = downstreamMeters[i].get("inputmeters");
for (var i = 0; i < inputMeters.length; i++) {
var flow = parseFloat(that.collection.get(inputMeters[i]).get("adjustedflow"));
sum += flow;
}
downstreamMeters[i].set({incrementalflow: sum});
}
is the same as this:
var i, sum, flow;
for (i = 0; i < downstreamMeters.length; i++) {
sum = 0;
inputMeters = downstreamMeters[i].get("inputmeters");
for (i = 0; i < inputMeters.length; i++) {
flow = parseFloat(that.collection.get(inputMeters[i]).get("adjustedflow"));
sum += flow;
}
downstreamMeters[i].set({incrementalflow: sum});
}
Now you can see that you are using exactly the same i in the outer and inner loops. On the first run through the loop, i will be inputMeters.length when you say downstreamMeters[i].set(...). Apparently, inputMeters.length > downstreamMeters.length so you end up running off the end of downstreamMeters; if you try to access an element of an array that is past the array's end, you get undefined and there's your
Cannot call method 'set' of undefined.
error.
Nesting loops is fine but you should be using different variables:
var i, j, sum, inputMeters;
for (i = 0; i < downstreamMeters.length; i++) {
sum = 0;
inputMeters = downstreamMeters[i].get("inputmeters");
for (j = 0; j < inputMeters.length; j++)
sum += parseFloat(that.collection.get(inputMeters[j]).get("adjustedflow"));
downstreamMeters[i].set({incrementalflow: sum});
}

Categories

Resources