scope of 3 dimensional array in javascript? - javascript

I'm trying to create a 3 dimensional array dynamicall in javascript based on a flat array of objects. after looping through the array, the array seems empty. If I print while in the loop, it seems to work, but then it seems to be gone and I want to return this to the caller. Help ?
//init the 3d array ??
this.teams = [];
for(var i = 0; i < sportsStandings.length; i++) {
var item = sportsStandings[i];
if(!this.teams[item.league])
this.teams[item.league] = new Array();
if(!this.teams[item.league][item.division])
this.teams[item.league][item.division] = new Array();
this.teams[item.league][item.division][this.teams[item.league][item.division].length]
= new Team(item.teamName, item.wins, item.losses);
console.log(this.teams); //this prints properly, and i see the 3d array grow
}
console.log('second' + this.teams); //this prints nothing

I cleaned up the code a bit, there is a couple of other ways to write it.
this.teams = [];
var teams = this.teams;
for(var i = 0; i < sportsStandings.length; i++) {
var ss = sportsStandings[i],
league = ss.league,
division = ss.division,
teamName = ss.teamName,
wins = ss.wins,
losses = ss.losses;
if (!teams[league]) {
teams[league] = {};
teams[league][division] = [];
} else if (!teams[league][division]) {
teams[league][division] = [];
}
var newTeam = new Team(teamName, wins, losses);
teams[league][division].push(newTeam);
}

Related

JavaScript interpolation and template literals not allowing me to push to array

I have a need for referencing an array name out of other variables values. Below is a simple program that doesn't push the value into an array. I was hoping someone could determine why. There is no runtime error but when you print the array it has not been pushed. I am creating a 4 person card game that currrently works by having a 2D array with 4 players. I want to deal the cards to P0cards P1Cards.... instead of the 2D players[[],[],[],[]] array.
My idea of using $p{i}.push(card) is not working
class Card{
constructor(suit, value){
this.value = value;
this.suit = suit;
}
}
let deck = [];
let players = [[],[],[],[]];
var p0Cards = [];
var p1Cards = [];
var p2Cards = [];
var p3Cards = [];
function deal(){
//players 1,2,3,4
for(let i = 0; i < 4; i++){
//cards 1,2,3,4,5,6
for(let j = 0; j < 6; j++){
let card = deck.pop();
//players[i].push(card);
`$p{i}.push(card)`; //this is what I would like to do.
}
}
}
Can you make your arr part of an object? Then you can access it with the use of a string.
let myVars = {}
myVars.arr = []
let x = 'arr';
myVars[x].push(2);
myVars.arr.push(3);
console.log(myVars.arr);
// myVars.arr = [2, 3]

use loop function that calls itself instead of nesting loops to iterate through object of objects of arrays, but running into async issues

I have an object called foods that contains different categories of foods as objects. Each of those object "categories" contains an array of food items in their respective categories. I'm trying to iterate through this, creating meal objects that include one food item from each category. I then take the meal objects and store them in a container array called meals. My goal is to have the container array contain every possible combo of food items. Instead of writing a series of nested loops, I'm trying to write one loop function that calls itself, but I think some index values increment faster than the loop function is called, giving me issues.
The nested loops below work. Note that the meals container array contains over 100 meal objects upon completion:
var meals = [];
var meal = {};
var foods = {veggies:["asparagus","broccoli"],meat:["chicken","steak"],dessert:["pudding","ice cream"]};
var keys = Object.keys(foods);
for (var i = 0; i < foods[keys[0]].length; i++) {
meal[keys[0]] = foods[keys[0]][i];
for (var j = 0; j < foods[keys[1]].length; j++) {
meal[keys[1]] = foods[keys[1]][j];
for (var k = 0; k < foods[keys[2]].length; k++) {
meal[keys[2]] = foods[keys[2]][k];
meals.push(JSON.parse(JSON.stringify(meal)));
}
}
}
This (below) is how I'm trying to do it using a loop function, but it does not work, as the meals container array contains far fewer than the number of possible combos upon completion. Is there a way to make something like this work using a callback, promise or something else?
var meals = [];
var meal = {};
var foods = {veggies:["asparagus","broccoli"],meat:["chicken","steak"],dessert:["pudding","ice cream"]};
var keys = Object.keys(foods);
function runLoop(foodTypeNumber) {
for (var i = 0; i < foods[keys[foodTypeNumber]].length; i++) {
meal[keys[foodTypeNumber]] = foods[keys[foodTypeNumber]][i];
if (keys.length > foodTypeNumber + 1) {
runLoop(foodTypeNumber + 1);
} else {
meals.push(JSON.parse(JSON.stringify(meal)));
}
}
}
runLoop(0);
I've also noticed that when I take the code above and increment foodTypeNumber right before the if statement, I get a different result. Can someone help me understand what is going on here?
var meals = [];
var meal = {};
var foods = {veggies:["asparagus","broccoli"],meat:["chicken","steak"],dessert:["pudding","ice cream"]};
var keys = Object.keys(foods);
function runLoop(foodTypeNumber) {
for (var i = 0; i < foods[keys[foodTypeNumber]].length; i++) {
meal[keys[foodTypeNumber]] = foods[keys[foodTypeNumber]][i];
foodTypeNumber++;
if (keys.length > foodTypeNumber) {
runLoop(foodTypeNumber);
} else {
meals.push(JSON.parse(JSON.stringify(meal)));
}
}
}
runLoop(0);

Creating variables from array

im really beginner into javascript so I struggle. My problem is - I created objects with constructor with specfic names of objects,
function Food (name, Cal, price, Fat, Carb, Protein, Sugar) {
this.name = name;
this.Cal = Cal;
this.price = price;
this.Fat = Fat;
this.Carb = Carb;
this.Protein = Protein;
this.Sugar = Sugar;
}
//bul
var bulPs = new Food("Bul"+" "+"Psz",120,3.50,36,80,45,78);
var bulSz = new Food("Bul"+" "+"Sez",140,2.90,34,75,33,68);
var bulBr = new Food("Bul"+" "+"bric",136,2.89,39,67,41,75);
var bulMa = new Food("Bul"+" "+"Man",157,3.20,42,56,36,78);
I have checkboxex, and when I click them i push chosen items (their id into array). Id of inputs are same as objects
Eg var bulMa and the id of this item is "bulMa".
When I try to call object's values with arrays index, it shows undiefined. Can someone tell me whats wrong ? Its because its outside of function fodd? Which part of JS core I should understand to handle those problems. Thanks
var zaz = [];
var inputs = document.getElementsByTagName('input');
for (var i=0; i< inputs.length; i++)
{
inputs[i].onfocus = function() {
zaznaczone.push(this.id);
console.log(zaz);
console.log(zaz[0].name);
};
}
Your array is called zaz, but you are pushing into zaznaczone.
Also zaz[0].name will be undefined; zaz[0] is the Id of the element and thus the name of your object.
var zaz = [];
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {
inputs[i].onfocus = function() {
zaz.push(this.id);
console.dir(zaz);
};
}

Rearranging Elements For Array of Array

I am trying to rearrange elements in an array of arrays but have been unsucessful. Can anyone offer suggestions? Here are two options I have tried. I want to swap/switch places for the first and second elements.
arr1 is an array of arrays (i.e. arr[][]) so I created arr2 to be an updated arr1
var arr2 = [];
for (var n = 0; n <arr1.length; n++){
arr2[n][0] = arr1[n][1];
arr2[n][1] = arr1[n][0];
}
The other thing I tried was:
function order(arr[]){
return [arr[n][1],arr[n][0], arr[n][2], arr[n][3]];
}
var arr2 = order(arr1);
You also need to create a new array for each item:
var arr2 = [];
for(var n = 0; n < arr1.length; n++) {
arr2[n] = [arr1[n][1], arr1[n][0]];
}
it's quite easy:
var a = arr1[n][0];
arr2[n][0] = arr1[n][1];
arr2[n][1] = a;
you need to save the first value as a variable, because if you do as you did(arr2[n][0] = arr1[n][1];), your two array indexes will have the same value.
You did:
a = 1, b = 2;
a = b;
b = a;
Which resolves in a = 2, b = 2
Also, your code as it is now, doesn't work. You need to create a new array for the simulation of multidimensional arrays in javascript.
for(i = 0; i < (yourdesiredamountofarrays); i++)
{
yourarray[i] = new Array();
}
The first example you need to use a temporary variable for the switch:
var arr2 = [];
for (var n = 0; n <arr1.length; n++){
var tempVal = arr1[n][1];
arr2[n][1] = arr1[n][0];
arr2[n][0] = tempArr;
}
The second example, in JS the variable shouldn't have brackets next to it, as it's just a loosely typed variable name.
function order(arr){
return [arr[n][1],arr[n][0], arr[n][2], arr[n][3], arr[n][4]];
}
var arr2 = order(arr1);
Next time, before asking you should check the console. The stackoverflow wiki page on JS has lots of great resources for learning to debug JS.

Add values to an array

How to add values to an empty array? I have tried the following but it is not working:
var student = [{}];
for (var i = 0; i < 5; i++) {
student[i].name = i;
student[i].id = "1";
student.push(student[i]);
}
var a = JSON.stringify(student);
alert(a);
It give output 6 time repeated last values not 5 time :
'[{"name":4,"id":"1"},{"name":4,"id":"1"},{"name":4,"id":"1"},{"name":4,"id":"1"},{"name":4,"id":"1"},{"name":4,"id":"1"}]'
var student = [{}];
This creates a javascript array containing one empty object
student[i].name = i;
student[i].id = "1";
For i = 0, this alters that empty object.
student.push(student[i]);
You then push that altered object to the array it already exists in. You now have two identical values in the array.
Two items after first push. This is repeated five times.
Pushing an item adds it to the array. There's usually no point in pushing an element that's already in the array. Create a new object and push that. The array doesn't have to be pre-populated with an empty object to modify.
var student = [];
for (var i = 0; i < 5; i++) {
student.push({
name: i,
id: '1'
});
}
In your original code, you are setting the object at student[i]'s values, then just pushing it again onto the array, then setting those values all over again.
You need to push a new object each time:
var student = [];
for (var i = 0; i < 5; i++) {
student.push({
id: i,
name: i
});
}
var a = JSON.stringify(student);
alert(a);
You are using the same name for the list and the new object. When you change the name of the list to students, your problem is fixed. Solution below:
var students = [{}];
for (var i = 0; i < 5; i++) {
student = {}
student.name = i;
student.id = "1";
students.push(student);
}
var a = JSON.stringify(students);
alert(a);
try ;
var students = [];
for (var i = 0; i < 5; i++) {
student = {}
student.name = i;
student.id = "1";
students.push(student);
}
var a = JSON.stringify(students);
alert(a);
Your array is not empty. It already contains an object. Maybe the problem is easier to see if we put the object in an extra variable and omit the the loop:
var student = [];
var obj = {};
obj.name = 1;
student.push(obj);
obj.name = 2;
student.push(obj)
The question is: How many objects are we creating here? The answer is one, namely var obj = {};. We then add some properties to the object (name) and add it to the array (student.push(obj)).
What comes next is crucial: We change the existing properties of the object and assign different values to it. Then we add the object to the array again. Even though student contains two elements, but they refer to the same value (which can be easily verified with student[0] === student[1]).
If you want to create an array of different objects, you have to create those objects. In our example this would be:
var student = [];
var obj = {};
obj.name = 1;
student.push(obj);
obj = {}; // <- create a new object
obj.name = 2;
student.push(obj)
For your code that means that you have to create a new object in each iteration of the loop, not just one outside of it.
Reading material about arrays and objects:
Eloquent JavaScript - Data structures: Objects and Arrays
MDN - Working with objects
MDN - Array object
Since you are pushing object, its reference change every time to current value so at last it shows the output as last value.
Try this
var student = [{}];
for (var i = 0; i < 5; i++) {
var obj = new Object();
obj.name = i;
obj.id = "1";
student.push(students);
}
var a = JSON.stringify(student);
alert(a);

Categories