Javascript multidimentional array undefined object error - javascript

I am trying to make a two dimensional array out of two one dimentional arrays with this code:
var PassAssoArr = new Array();
for(k in PassPourcentNames) {
PassAssoArr[k][0] = PassPourcentNames[k]
PassAssoArr[k][1] = PassPourcentValue[k]
}
However, I get the error message: " 'undefined' is null or not an object " and it points to the first line after the for statement.
PassPourcentNames and PassPourcentValue have the same number of elements and none of the values are null. The first one contain strings and the second one integers.
Any help is greatly apreciated.

var PassAssoArr = new Array();
for(k in PassPourcentNames) {
PassAssoArr[k] = new Array();
PassAssoArr[k][0] = PassPourcentNames[k]
PassAssoArr[k][1] = PassPourcentValue[k]
}
Also instead of new Array() you can use []
var PassAssoArr = [];
for(k in PassPourcentNames) {
PassAssoArr[k] = [];
PassAssoArr[k][0] = PassPourcentNames[k]
PassAssoArr[k][1] = PassPourcentValue[k]
}
I believe this is actually faster in most JS engines.

First define PassAssoArr[k] = []; before assigning to [0] and [1].

Javascript does not support true multi-dimensional arrays.
You're trying to use nested arrays without creating the inner arrays.
You need to put an array into each element of the outer PassAssoArr:
PassAssoArr[index] = []; //Empty array literal

You're only defining one dimension of PassAssoArr - you need to set PassAssoArr[k] = new Array();

Try just doing:
PassAssoArr[k] = new Array(PassPourcentNames[k], PassPourcentValue[k]);

Related

JSON stringify does not convert array [duplicate]

In the example below, the array2.length is only 10, while in my mind, it should be 13.
Why does the "string keyed" indexes not increase the length of the array?
I can store things and still access it, and the VS debugger shows that those arrays are being stored properly. So why is the length not increased?
var array2 = new Array();
array2["a"] = new Array();
array2["b"] = new Array();
array2["c"] = new Array();
for (var i = 0; i < 10; ++i)
array2[i] = new Array();
var nothing = "";
for (var i = 0; i < array2.length; ++i)
nothing = "";
Javascript arrays cannot have "string indexes". A Javascript Array is exclusively numerically indexed. When you set a "string index", you're setting a property of the object. These are equivalent:
array.a = 'foo';
array['a'] = 'foo';
Those properties are not part of the "data storage" of the array.
If you want "associative arrays", you need to use an object:
var obj = {};
obj['a'] = 'foo';
Maybe the simplest visualization is using the literal notation instead of new Array:
// numerically indexed Array
var array = ['foo', 'bar', 'baz'];
// associative Object
var dict = { foo : 42, bar : 'baz' };
Because the length is defined to be one plus the largest numeric index in the array.
var xs = [];
xs[10] = 17;
console.log( xs.length ); //11
For this reason, you should only use arrays for storing things indexed by numbers, using plain objects instead if you want to use strings as keys. Also, as a sidenote, it is a better practice to use literals like [] or {} instead of new Array and new Object.
You're not adding items to the array; you're adding properties to the Array object.
As said above, use object for associative arrays.
If you don't you won't necessarily notice you're doing it wrong, until you innocently use "length" as an array index :
var myArray = [];
myArray["foo"] = "bar"; //works
console.log(myArray["foo"]) //print "bar"
myArray["length"] = "baz" //crash with a "RangeError: Invalid array length"
That is because you are replacing the length attribute of an array with a String, which is invalid.
"string keyed" indexes are not indexes at all, but properties. array2["a"] is the same as saying array2.a. Remember that you can set properties on any kind of variable in javascript, which is exactly what you're doing here.
You can push object to array, it will automatically get indexed (integer). If you want to add index as you want then you want to make it as object
If you want to use an object's properties as if they were like instances of a string indexed array, the work around for the length is:
var myArray = new Array();
myArray["a"] = 'foo';
myArray["b"] = 'bar';
myArray["c"] = 'baz';
let theLength = Object.keys(myArray).length

How to create data model dynamically

I have this Json data I get from server in javascript
var mydata = JSON.parse('["X","Y","Z"]');
Below I have the following data model in javascript..
var mySchemasList = {
schemas: [new SelectSchemaModel("A", false),
new SelectSchemaModel("B", false),
new SelectSchemaModel("C", false)
]
};
I want to create this model dynamically by getting data ('A','B','C') from mydata..
Any help is sincerely appreciated..
Thanks
Can't you just do something like the following?
var i
var mySchemaList = {schemas:[]};
for (i = 0; i < mydata.length; i++) {
mySchemaList.schemas.push( new SelectSchemaModel(mydata[i], false) );
}
In javascript, objects and arrays are accessed using the . or [] operators. The following two lines does exactly the same thing:
mySchemasList.schemas;
mySchemasList['schemas'];
Also, each member of an object or array act like a variable on its own. So you can assign values, objects or arrays to them:
mySchemasList = {};
When a variable (or property) is declared but not assigned anything its value is undefined. So you can check simply by:
if (mySchemasList === undefined) mySchemasList = {};
Alternatively you can use || short circuiting since undefined is considered false:
mySchemasList = mySchemasList || {};
putting this all together, the following two examples does exactly the same thing.
Example 1:
var mySchemasList = {
schemas : []
}
Example 2:
var mySchemasList = {};
mySchemasList.schemas = [];
Now that you've created an array at mySchemasList.schemas you can start pushing other objects into it:
mySchemasList.schemas.push(new SelectSchemaModel("A", false));
mySchemasList.schemas.push(new SelectSchemaModel("B", false));
mySchemasList.schemas.push(new SelectSchemaModel("C", false));
Wrapping it up in a for loop parsing the JSON data, you'd do this:
var mydata = JSON.parse(ajax.responseText);
for (var i=0; i<mydata.length; i++) {
mySchemasList.schemas.push(new SelectSchemaModel(mydata[i],false));
}

Push to a javascript array if it exists, if not then create it first

Is there a way for this line to always work and not throw TypeError: Cannot read property 'Whatever' of undefined
var MyArray = [];
MyArray[StringVariableName][StringVariableName2].push("whatever");
Try this:
var MyArray = [];
MyArray[StringVariableName] = MyArray[StringVariableName] || [];
MyArray[StringVariableName][StringVariableName2] = MyArray[StringVariableName][StringVariableName2] || [];
MyArray[StringVariableName][StringVariableName2].push("whatever");
You could even, through the power of expressions, do this with a one-liner.
(MyArray[StringVariableName][StringVariableName2] || (MyArray[StringVariableName][StringVariableName2] = [])).push("whatever");
You could use the literal syntax to set things up like you'd have them:
var myObj = {
StringVariableName: {
StringVariableName2: []
}
};
myObj.StringVariableName.StringVariableName2.push("whatever");
I think instead of using array in the first place, use object if your keys are not integers.
In Javascript Arrays are also object So it is not wrong to do this
var a = [];
a['key'] = 'something';
console.log(a); //Gives []
I think it is conceptually wrong So instead of using Array to hold such pair of data you should use objects. See this:
var myObject = myObject || {};
myObject[str1] = myObject[str1] || {};
myObject[str1][str2] = myObject[str][str2] || [];
// Now myObject[str1][str2] is an array. Do your original operation
myObject[str1][str2].push("whatever");
To check without getting an error:
this snippet allows you to check if a chained object exists.
var x;
try{x=MyArray[name1][name2][name3][name4]}catch(e){}
!x||(x.push('whatever'));
from
https://stackoverflow.com/a/21353032/2450730
Shorthand creation of object chains in Javascript
this function allows you to create chained objects with a simple string.
function def(a,b,c,d){
c=b.split('.');
d=c.shift();//add *1 for arrays
a[d]||(a[d]={});//[] for arrays
!(c.length>0)||def(a[d],c.join('.'));
}
usage
var MyArray={};//[]
def(MyArray,'name1.name2.name3.name4');//name1+'.'+name2....
from
https://stackoverflow.com/a/21384869/2450730
both work also for arrays with a simple change.replace {} with []
if you have any questions just ask.

How to create empty 2d array in javascript?

How do I create an empty 2D array in Javascript (without knowing how many rows or columns there will be in the new array)?
If it's a simple array var newArray = new Array(); I can assign as many elements as I want. But what about a 2D array? Can I create one without specifying the numbers of rows and columns? and how do I access the elements afterwards (myArray[0][1] or myArray[0,1])?
You can create a 6 x 6 empty array like this:
var myGrid = [...Array(6)].map(e => Array(6));
Array(6) generates an array with length = 6 and full of undefined values.
We map that array to another array full of undefined values.
In the end, we get a 6x6 grid full of undefined positions.
If you need to initialize the grid with a default value:
var value = 'foo'; // by default
var myGrid = [...Array(6)].map(e => Array(6).fill(value));
Now you have a 6 x 6 grid full of 'foo'.
Yes you can create an empty array and then push data into it. There is no need to define the length first in JavaScript. Check out jsFiddle Live Demo
Define:
const arr = [[],[]];
Push data:
arr[0][2] = 'Hi Mr.A';
arr[1][3] = 'Hi Mr.B';
Read data:
alert(arr[0][2]);
alert(arr[1][3]);
Update:
Here is also a video recommended by Brady Dowling:
Create a 2D array: ([https://www.youtube.com/watch?v=tMeDkp1J2OM][2])
There are no two dimensional arrays in Javascript.
To accomplish the effect of a two dimensional array, you use an array of arrays, also known as a jagged array (because the inner arrays can have different length).
An empty jagged array is created just like any other empty array:
var myArray = new Array();
You can also use an empty array literal:
var myArray = [];
To put any items in the jagged array, you first have to put inner arrays in it, for example like this:
myArray.push([]);
myArray[0][0] = 'hello';
You can also create an array that contains a number of empty arrays from start:
var myArray = [[],[],[]];
That gives you a jagged array without any items, but which is prepared with three inner arrays.
As it's an array of arrays, you access the items using myArray[0][1].
Say you wanted to make a 2d array (i.e. matrix) that's 100x100, you can do it in one line, like this:
var 2darray = new Array(100).fill(null).map(()=>new Array(100).fill(null));
This will create a 100x100 matrix of NULL's.
Replace the 100x100 with whatever dimensions you want, and the null's with whatever is your prefered default value, or blank for undefined.
You can use a simple for loop to create an array of the approximate size and then push more rows if need be.
const arr = [];
const n = 7;
const m = 5;
for (let i = 0; i < n; i++) {
arr.push(new Array(m).fill(0));
}
const arr = [];
const n = 7;
const m = 5;
for (let i = 0; i < n; i++) {
arr.push(new Array(m).fill(0));
}
console.log(arr);
var myArray = [
["cats","dogs","monkeys","horses"],
["apples","oranges","pears","bananas"]
];
document.write(myArray[0][2]) //returns "monkeys"
Two things:
1) The array length property improperly reports the array length if called after the var myArray = [[],[]]; statement. Technically, since the empty arrays are defined, they are getting counted by the length property, but in the spirit of the length property it really should return 0, because no non-empty elements have been added to any of the arrays.
A minimum work around is to use two nested for( in ) loops, one for the 1st array and one for the 2nd array, and to count the non-undefined elements.
2) Extending Siamak A.Motlagh example and adding a arr([2][4]) = 'Hi Mr.C'; assignment fails with an "Uncaught TypeError: Cannot set property '4' of undefined" error.
See the jsFiddle: http://jsfiddle.net/howardb1/zq8oL2ds/
Here is a copy of that code:
var arr = [[],[]];
alert( arr.length ); // wrong!
var c = 0;
for( var i in arr )
for( var j in arr[ i ] )
if( arr[ i ][ j ] != undefined )
++c;
alert( c ); // correct
arr[0][2] = 'Hi Mr.A';
alert(arr[0][2]);
arr[1][3] = 'Hi Mr.B';
alert(arr[1][3]);
arr[2][4] = 'Hi Mr.C'; // At this point I'm getting VM558:62 Uncaught TypeError: Cannot set property '4' of undefined
alert(arr[2][4]);
var c = 0;
for( var i in arr )
for( var j in arr[ i ] )
if( arr[ i ][ j ] != undefined )
++c;
alert( c );
Why does the third assignment fail? What about the [[],[]] creation statement told it that the first array was valid for 0 and 1, but not 2 or that 2 and 3 were ok for the second array, but not 4?
Most importantly, how would I define an Array in an Array that could hold date objects in the first and second arrays. I'm using the jQuery-UI DatePicker, which expects an array of dates, as in date objects, which I've extended to use a second date array to contain date objects that contain times so I can keep track of multiple dates, and multiple times per day.
Thanks.
The functions I use
function get_empty_2d_array(numRows, numColumnns) {
return [...Array(numRows)].map(e => Array(numColumnns));
}
function get_2d_array_filled(numRows, numColumnns, fillValue) {
return [...Array(numRows)].map(e => Array(numColumnns).fill(fillValue));
}
This also works as an expression:
var twoDarr= new Array(desiredLength);
for (i=0;i<twoDarr.length;i++) {twoDarr[i]=[];}
I don't know how it pars in terms of performance with the rest of the answers here, if you have a clue let me know in the comments.
If you don't know the length of the array beforehand pls have in mind that you can use either push([]), or splice() if you want to push/remove/replace a new element in place of an existing one.
const grid = new Array(n).fill(new Array(n))

Why does a string index in an array not increase the 'length'?

In the example below, the array2.length is only 10, while in my mind, it should be 13.
Why does the "string keyed" indexes not increase the length of the array?
I can store things and still access it, and the VS debugger shows that those arrays are being stored properly. So why is the length not increased?
var array2 = new Array();
array2["a"] = new Array();
array2["b"] = new Array();
array2["c"] = new Array();
for (var i = 0; i < 10; ++i)
array2[i] = new Array();
var nothing = "";
for (var i = 0; i < array2.length; ++i)
nothing = "";
Javascript arrays cannot have "string indexes". A Javascript Array is exclusively numerically indexed. When you set a "string index", you're setting a property of the object. These are equivalent:
array.a = 'foo';
array['a'] = 'foo';
Those properties are not part of the "data storage" of the array.
If you want "associative arrays", you need to use an object:
var obj = {};
obj['a'] = 'foo';
Maybe the simplest visualization is using the literal notation instead of new Array:
// numerically indexed Array
var array = ['foo', 'bar', 'baz'];
// associative Object
var dict = { foo : 42, bar : 'baz' };
Because the length is defined to be one plus the largest numeric index in the array.
var xs = [];
xs[10] = 17;
console.log( xs.length ); //11
For this reason, you should only use arrays for storing things indexed by numbers, using plain objects instead if you want to use strings as keys. Also, as a sidenote, it is a better practice to use literals like [] or {} instead of new Array and new Object.
You're not adding items to the array; you're adding properties to the Array object.
As said above, use object for associative arrays.
If you don't you won't necessarily notice you're doing it wrong, until you innocently use "length" as an array index :
var myArray = [];
myArray["foo"] = "bar"; //works
console.log(myArray["foo"]) //print "bar"
myArray["length"] = "baz" //crash with a "RangeError: Invalid array length"
That is because you are replacing the length attribute of an array with a String, which is invalid.
"string keyed" indexes are not indexes at all, but properties. array2["a"] is the same as saying array2.a. Remember that you can set properties on any kind of variable in javascript, which is exactly what you're doing here.
You can push object to array, it will automatically get indexed (integer). If you want to add index as you want then you want to make it as object
If you want to use an object's properties as if they were like instances of a string indexed array, the work around for the length is:
var myArray = new Array();
myArray["a"] = 'foo';
myArray["b"] = 'bar';
myArray["c"] = 'baz';
let theLength = Object.keys(myArray).length

Categories