how to generate arrays automatically in javascript? - javascript

I want to make a loop that makes arrays automatically and assign the values to it.
The problem is how to generate the array itself automatically.
for(var attGetter=1; attGetter <= num; attGetter++){
var catesArray1 = new Array();
for(var atttGetterArray=1; atttGetterArray <= series; attGetterArray++){
idOfInput = "cate"+chartGetter+"_series"+attGetterArray;
catesArray1.push($("#"+idOfInput).val());
}
}
I want the loop to generate the array itself automatically like
catesArray1
catesArray2
catesArray3
and so on..

You need an object or an array to hold the multiple arrays you wish to create. Maybe something you are looking for is like the following?
var arrayHolder = new Array();
for(var attGetter=1; attGetter <= num; attGetter++){
var catesArray = new Array();
for(var attGetterArray=1; atttGetterArray <= series; attGetterArray++){
idOfInput = "cate"+chartGetter+"_series"+attGetterArray;
catesArray.push($("#"+idOfInput).val());
}
arrayHolder.push(catesArray);
}

If you want the arrays to be in global namespace, You can try
window['catesArray' + attGetter] = [];
...
window['catesArray' + attGetter].push(...)
Else you can create a hash object and use it to hold the reference
var obj = {};
.....
obj['catesArray' + attGetter] = [];
.....
obj['catesArray' + attGetter].push(...)

In that case you will have to create one new array that holds all the cacatesArrays from first for loop
var catesArrayContainer = new Array(); //<<<---------------------
for(var attGetter=1; attGetter <= num; attGetter++){
var catesArray = new Array();
for(var atttGetterArray=1; atttGetterArray <= series; attGetterArray++){
idOfInput = "cate"+chartGetter+"_series"+attGetterArray;
catesArray.push($("#"+idOfInput).val());
}
catesArrayContainer.push(catesArray); //<<<--------------------
}
EDIT :
This happens because the scope of variable catesArray1 was limited. When the loop enters next iteration the catesArray1 gets reinitialized, thus losing all the previously stored values...
Now in the code I have posted, we are storing every instance of catesArray1 in another array, and your values persist out side of the for loop

You can do something like this for 4 arrays of 5 elements each
yourarray=[];
for (i = 0; i <4; i++) {
temparray=[];
for (j = 0; j < 5; j++) {
temparray.push($('#'+whateverID+'_'+i+'_'+j)) //your values here
}
yourarray.push(temparray);
}
Check it on this JSFiddle. open chrome console to see array
If you want to create array within loop from index
You can use eval to evaluate javascript from strings but i wont use that unless there is no other way. you can see both above and eval method in this Fiddle. Open Chrome console to see array values
Just a comparison of using eval and 2D array
Open console in chrome while you run this jsFiddle and you will see the difference in eval and 2darray in context of this question.

You should assign them to an object. In this case, make an object variable before the first for-loop to hold all arrays:
var allArrays = {};
for(var attGetter=1; attGetter <= num; attGetter++){
var currentArray = allArrays['catesArray' + attGetter] = new Array();
for(var atttGetterArray=1; atttGetterArray <= series; attGetterArray++){
idOfInput = "cate"+chartGetter+"_series"+attGetterArray;
currentArray.push($("#"+idOfInput).val());
}
}

Instead of attempting to create & allocate dynamically named variables, I would think of this more of an array of array's if you will. In other words, create an array that holds all of the arrays you want:
var collections = []; // Literal notation for creating an array in JS
From here, it's a matter of making each value you create within this array its own array:
var n = 10; // Total amount of arrays you want
for (var i = 0; i < n; i++) {
var values = [];
// Have another loop that fills in the values array as expected
collections.push(values); // Each element at collections[i] is its own array.
}
If you truly need named elements, you could potentially do something very similar with just an object {} instead, and refer to each element by a name you create.
var collections = {}; // Literal notation for an object in JS
var n = 10; // Total amount of arrays you want
for (var i = 0; i < n; i++) {
var values = []; // Literal notation for an array in JS
// Fill in the values array as desired
var name = 'arr' + i; // How you'll refer to it in the object
collections[name] = values;
}
I suggest the former though, since it does not sound like you need to have explicit names on your arrays, but just want multiple layers of arrays.

Related

Sorting custom objects - couple of items always end up out of place

I am trying to sort a 2D array of custom objects, inside each inner array, based on one of the properties. This sub-arrays each represent one class, the outer array all the classes in the school. My strategy is as such:
Make a copy of the arry to provide a framework with the correct number of subarrays and indeces
Pass a copy of the sub-array to variable
Iterate over that array (the class) and pull out the last name from the object (which holds a number of other pieces of data on the child) and place it in an array that will be the index
Sort the index
Iterate over the class array, find the position of the last name in the index array, and insert the object into that index into the copied 'school'.
But this is not working. In some instances, one or two objects end up in the wrong place, in other instances it completely out of order. I have tried inspecting my index and comparing it with the 2D array, but the index is correct and I can't figure out why its not working. Here is the code:
var studentsInClass = // I have a function here that returns the 2D array of classes containing custom objects
var sortedStudentsInClass = studentsInClass;
var singleClassHolder = [];
var studentIndex = [];
// each iteration is for a single class
for(var i = 0; i < studentsInClass.length; i ++){
studentIndex = [];
singleClassHolder = studentsInClass[i];
// populate the student reference index
for(var j = 0; j < singleClassHolder.length; j++){
studentIndex.push(singleClassHolder[j].ID);
}
studentIndex.sort();
// iterate through students of single class, placing them in alphabetical order
for(var k = 0; k < singleClassHolder.length; k++){
sortedStudentsInClass[i][studentIndex.indexOf(singleClassHolder[k].ID)] = singleClassHolder[k];
}
}
return sortedStudentsInClass;
}
In case the object is important:
function Child(last, first, id, classroom, serviceDays, eligibility){
this.lastName = last;
this.firstName = first;
this.ID = id;
this.class = classroom;
this.maxServiceDays = serviceDays;
this.eligibility = eligibility;
}
And just a side note, it may seem extraneous having created the new singleClassHolder variable. After I noticed I did that, I removed it and just iterated through the 2D array, but that resulted in even more elements out of place.
Make a copy of the arry
var sortedStudentsInClass = studentsInClass;
This won't make a copy. It only makes one variable reference the other in memory. They both refer to the same array in memory. See related answer here.
The easiest way to fix the code is by declaring sortedStudentsInClass as a new array.
var studentsInClass = get2DArrayOfClasses();
var sortedStudentsInClass = [];
/*...*/
for(var k = 0; k < singleClassHolder.length; k++){
sortedStudentsInClass[i] = sortedStudentsInClass[i] || [];//declare inner array, if not present
sortedStudentsInClass[i][studentIndex.indexOf(singleClassHolder[k].ID)] = singleClassHolder[k];
}

Creating many random arrays for use as elements in another array

Consider:
var main = []
Now I want to generate many (289 to be exact) Arrays to be elements in the main one. Each of these arrays will have be like:
var subobject = {x:"A", y:"B", terrain:"C", note:"D"}
Generating the values are no problem, and I can easily put those values in a already defined subobject = {} and push(), but I can't figure out how to iterate a script each time which creates a new object and then push() into var main.
The naming of the subobject is unimportant, I'm looking for solution inwhich I can pull specific information such as:
main[0].x // get x value of the subarray in 0 location in main
main[5].note// get note value of the subarray in 5 location in main
(would it make a difference if every array had the same name? since I would never access subobject directly (after being pushed into main), but through main[X].YYY or would it have to be via main[X].subarray[Y] ?)
for (var i = 0; i < 289; i++) {
main.push({x: getRandomX(), y: getRandomY(), terrain: getTerrain(), note: ""});
}
as long as you create new objects {} before you push them to the array it is ok.
it doesn't matter if you assign the new object to the same variable (ie subobject)
you access them later like this:
main[0].x // get the value of x of the first element
[x:"A", y:"B", terrain:"C", note:"D"] isn't valid javascript, I think you want an object here:
{x:"A", y:"B", terrain:"C", note:"D"}
And to push each generated value, you can use a for loop
for (var i = 0; i < 9; i++) {
//do something, for example, generate a value
}
Arrays are only numerically indexed.
If you want named keys you have to use objects.
Here's the wrong way to do it.
var main = [],
subobject = {x:"A", y:"B", terrain:"C", note:"D"};
for(var i=0; i<289; i++){
subobject["x"] = Math.random();
subobject["terrain"] = Math.random();
//continue adding values using keys
main.push(subobject);
}
The thing is if you just use the same object your going to access that object every time you iterate it, and you'll replace it's value.
So you should do it like this.
var main = [],
subobject = {};
for(var i=0; i<289; i++){
subobject = {};//new object to make for uniquness
subobject["x"] = Math.random();
subobject["terrain"] = Math.random();
//continue adding values using keys
main.push(subobject);
}
You access members like this.
main[0].x;//value of x at index 0
//next index
main[1].terrain;//value of terrain at index 1
Collisions will only happen if you set the same index twice.
main[2].x = "value";
main[2].x = "replace value by accident";
Unless you want to change the value for some reason.
A different index will always give you a different object if you set a different one each time.

Can't reference array by index

I have an array defined as:
var subjectCache = [];
I then have some code to build it up, which is working ok.
However, if I try to reference the array by an index, e.g.:
var x = subjectCache[0];
or
var x = subjectCache[1];
I get undefined.
Also subjectCache.length is always 0 (zero).
if I try to reference it by its key, e.g.:
var x = subjectCache['12345'];
it works.
Is this normal? Shouldn't I be able to reference it by its index whatever?
I'm using Internet Explorer, if it makes a difference (and it probably does :( )
[Edit]
this is the code I'm using to build the array, although I really don't think it is to blame.
It's a callback from a webservice call. This is working fine and the array is being populated.
var subjectCache = [];
var subjectCacheCount = 0;
function refreshSubjectsCallback(data) {
// update subjects
// loop through retrieved subjects and add to cache
for( i=0; i < data.length; i++ )
{
var subject = data[i];
var subjectid = subject.SubjectId;
subjectCache[subjectid] = subject;
subjectCacheCount += 1;
}
}
[/Edit]
You're probably assigning keys manually instead of using subjectCache.push() to add new elements to the array:
var array = [];
array['foo'] = 'bar';
console.log(array.length); // 0
The length attribute isn't going to reflect those changes the way you'd expect:
> var a = [];
undefined
> a[100] = 2; // The previous `100` entries evaluate to `undefined`
2
> a.length;
101
Instead, use an object:
var object = {};
object['foo'] = 'bar';
for (var key in object) {
var value = object[key];
console.log(value);
}
From your symptoms, it sounds like you are trying to treat the array as an associative array.
In Javascript, arrays work like this:
var a = [];
a[1] = 10;
alert(a.length);
Objects work like this:
var o = {};
o.myProp = true;
o["myOtherProp"] = false;
Arrays only work with numeric keys not strings. Strings assign properties to the object, and aren't counted as part of length nor it's numeric indices.
When building the array, make sure you are assigning to a numeric position within the array.
No, it will not work, because you haven't created arrays but objects.
you will have to access it by its key.
var x = subjectCache['12345'];
If this works and subjectCache.length doesn't, I think you are making an object not an array. You are confused.
Somewhere along the road you lost the array, and the variable subjectCache points to a different kind of object.
If it was an array, it can't have the length zero and contain an item that is reachable using subjectCache['12345']. When you access an item in an array it doesn't make any difference if you use a numeric index or a string representing a number.

Convert multidimensional array to array of objects in javascript

I have a multidimensional array (retdata[R][C]) that basically looks like a spreadsheet of cells. R represents the rows, C the columns. I want to create an array of objects so that I get the following
[{retdata[1][1]:retdata[2][1],retdata[1][2]:retdata[2][2],retdata[1][3]:retdata[2][3] },
{retdata[1][1]:retdata[3][1],retdata[1][2]:retdata[3][2],retdata[1][3]:retdata[3][3] },
{retdata[1][1]:retdata[4][1],retdata[1][2]:retdata[4][2],retdata[1][3]:retdata[4][3] },
etc...
]
The resulting array should be:
[{"Col1":"dataR2C1","Col2":"dataR2C2", "Col3":"dataR2C3"},
{"Col1":"dataR3C1","Col2":"dataR3C2", "Col3":"dataR3C3"},
{"Col1":"dataR4C1","Col2":"dataR4C2", "Col3":"dataR4C3"},
etc...
]
I have tried a number of options without success. Any help would be greatly appreciated.
Here is one example I have used but it id not serializing the objects properly.
var TABLE = [];
for (var i=2; i<=rows; i++) {
var ROW = {};
for (var j=1; j<=columns; j++){
name = retdata[1][j].toString;
value = retdata[i][j].toString;
ROW += {name: value}
}
TABLE += ROW;
}
This is like a CSV-parser, the first row of your table are the keys for the line-objects. Your function would work, but you need to correct your array indices: they always start at 0, running up to n-1. Also, you need to learn a bit JavaScript syntax:
something.toString does not call the toString function on that value, but gets that function (it's just an object).
You don't need toString at all - where needed, values are automatically casted
You can't add key-value-pairs to object with a simple operator. You will need to assign the value to that property of an object, with the bracket notation. The += operator would have casted the values to strings and concatenated them.
It's the same with arrays. You could use the .push() method, or just assign to a numerical key - the javascript array object will automatically update its length.
var retdata = […];
var table = [],
keys = retdata.shift(); // get & remove the first row
for (var i=0; i<retdata.length; i++) {
var row = {};
for (var j=0; j<retdata[i].length; j++)
row[ keys[j] ] = retdata[i][j];
table[i] = row;
}
Thank you Bergi. Here is my final solution:
var TABLE = [];
for (var i=2; i<=rows; i++) {
var ROW = {};
for (var j=1; j<=columns; j++){
ROW [retdata[1][j]] = retdata[i][j];
}
TABLE[i]= ROW;
}
which works. The shift did not work as expected but above code is just what I needed. Thanks!

Syntax for iterating the comparison of one array to many other systematically named arrays

I have a question about proper syntax in iterative functions. I want to compare one master array to a large set (180+) of other arrays. The large set of arrays to be compared are systematically named (scorespec1, scorespec2, scorespec3...). Each comparison will be made not one-to-one but through an algorithm and then have the results stored in another set of arrays that are also systematically named for later query. I not worried about getting the algorithm right just yet. I'm just not sure of the proper syntax to iterate through my arrays. For instance, this is but one of the syntax structures I have tried but failed to get working:
for (i=01;i=186;i++){
if (scorespec+(i)[04]=unknownspec[16]){
resultarray+(i)[01]=True;
else
resultarray+(i)[01]=False;}}
My main problem here is I don't know how to structure the syntax to include the counter variable in my for-loop in the variable name. I've tried a variety of different syntaxes in addition to what I show above and it just doesn't seem to work right. What syntax should I be using?
There are three parts to the for statement:
for ([initialExpression]; [condition]; [incrementExpression]) {
// The statement (i.e. what will happen on each iteration)
}
To iterate through an array, we need the length of the array and a counter which will move towards that length as we iterate. This is the usual pattern:
var myArray = ['foo', 'bar', 'far']; //...
for (var i = 0; i < myArray.length; i++) {
myArray[i]; // <- this is the current array item
}
It's sensible to cache the array's length like so:
for (var i = 0, l = myArray.length; i < l; i++) {
myArray[i]; // <- this is the current array item
}
Also, FYI, your booleans, true and false, should not be capitalised.
If you had declared your array in global scope you could access them using the window object:
var scorespec1 = "123";
var scorespec2 = "456";
for ( var i = 1; i < 3; i++ ){
alert(window['scorespec' + i]);
}
Or you could use the slow and evil eval:
var scorespec1 = "123";
var scorespec2 = "456";
for ( var i = 1; i < 3; i++ ){
var scorespec;
eval("scorespec = scorespec" + i);
alert(scorespec);
}

Categories

Resources