Javascript multi-dimension array initialization - javascript

I'm looking for the best way to initialize multi-dimensional arrays in Javascript. I'm much more familiar with PHP where I'm not obliged to declare arrays or dimensions before feeding it with values.
Basically what I tried to do is create an array with the following format
catalogue[i]["name"]="a name";
catalogue[i]["description"]="a description";
...etc...
If I do the following:
var catalogue = new Array();
for (i=0; i<otherarray.length;i++)
{
catalogue[i]['name']=otherarray[i];
}
Catalogue is undefined, I also tried with catalogue[i].name but same issue. If I only assign a simple value like catalogue[i]=2, it works but that's not what I'm looking for. I couldn't find a working example of what I'm looking for.
Do I need to initialize every possible dimension of an array before being able to feed it with new values?
Thanks
Laurent

var catalogue = new Array();
for (i = 0; i < otherarray.length; i++) {
catalogue[i] = {};
catalogue[i]['name'] = otherarray[i];
}
Or
var catalogue = new Array();
for (i = 0; i < otherarray.length; i++) {
catalogue.push({"name":otherarray[i]});
}

Put this in your loop to create the object you want to store the values in:
catalogue[i] = {}; OR catalogue.push({});
Your code would be like this then:
var catalogue = new Array();
for (i=0; i<otherarray.length;i++)
{
catalogue[i] = {}; // initialization
catalogue[i]['name']=otherarray[i];
}
Note that you can initialize and assign a value in the same line:
var catalogue = new Array();
for (i=0; i<otherarray.length;i++)
{
catalogue[i] = {
name: otherarray[i],
otherKey: 'otherValue' // list all of your keys and values
};
}

If you want string keys in your array in Javascript you have to declare an Object. The catalogue variable itself is an array but each element inside that array is an object with the two keys "name" and "description". For example this code works :
var c = [1,2,3,4,5];
var n = ['one', 'two', 'three', 'four', 'five'];
var cat = [];
for (i = 0; i < c.length; i++)
{
cat[i] = {
name : n[i],
value: c[i]
};
}
now if you console.dir(cat); it outputs this result :
Array[5]
-> 0 : Object
name: "one"
value: 1
-> 1 : Object
name: "two"
value: 2
...

Related

Js: multidimensional array literal declared: Add elements

I wanted to know if its possible to ad elements to an array which is declared as the following...
Please check the add() function, I can't figure out how to solve this problem. Thanks
It's not necessary, but I'd appreciate if you give an explanation since of c++ point of view programmer.
// My array is this way declared
var myArray = [
['John', 'Doe', '1980'],
['Jane','Malloy','1982'],
['Vincent','Malloy','1972']
];
// then I want to add a new elements in it, but It seems to doesn't work
var add = function() {
//var textbox = document.getElementById('textbox').value;
// storing new person in array
myArray [3][0] = 'New1';
myArray [3][1] = 'New2';
myArray [3][2] = 'New3';
};
//finally this function is for displaying the elements of myArray
var show = function() {
// clean output
document.getElementById('output').innerHTML = '';
// delay time
setTimeout (function() {
// showing info. people
for (var i in myArray) {
for (var j in myArray)
document.getElementById('output').innerHTML += myArray[i][j] + ' ';
document.getElementById('output').innerHTML += '<br/>';
}
}, 250);
};
So right here:
var add = function() {
//var textbox = document.getElementById('textbox').value;
// storing new person in array
myArray [3][0] = 'New1';
myArray [3][1] = 'New2';
myArray [3][2] = 'New3';
};
You can't add to myArray[3] because myArray[3] is undefined. You need to assign an empty array to myArray[3] first:
myArray [3] = [];
myArray [3][0] = 'New1';
myArray [3][1] = 'New2';
myArray [3][2] = 'New3';
Or more generally, assuming the idea is to add to the end of your array, you could do something like:
var idx = myArray.length;
myArray[idx] = [];
myArray[idx][0] = "New 1";
// ...
Or even something like:
var newArray = ["New1", "New2", "New3"];
myArray.push(newArray);

How can I create an new array for each specific data in a loop in javascript?

I have this function:
flotLinea:function(tareas){
var self = this;
console.info(tareas);
var aTar = new Array();
for(var i = 0;i<tareas.length;i++){
var val = new Array(new Date(tareas[i].fecha_registro),tareas[i].porcentaje);
aTar.push(val);
}
console.info(aTar);
},
Using console.info(tareas); print this :
And using console.info(aTar); print :
(The data from tareas always is changing because the data comes from a dropdown)
I need create an new array for each id_usu using the same data , how can I do this?
For example in this case I need an array for id_usu = 4 ( are two id_usu = 4, so i need the data where id_usu = 4) , one array with id_usu = 6 and one array with id_usu = 9
I need do this , because this data are for a chart, so, after , each user ( id_usu ) will be a different color in that chart.
From whatever I have understood form your problem statement and the code you have provided, I've provided a solution below.
flotLinea:function(tareas){
var self = this;
console.info(tareas);
var aTar = new Array();
var idArray = [];
for(var i = 0;i<tareas.length;i++){
if(idArray.indexOf(tareas[i].id_usu) == -1){
var val = new Array(new Date(tareas[i].fecha_registro),
tareas[i].porcentaje);
idArray.push(tareas[i].id_usu);
aTar.push(val);
}
else{
for(var j = 0; j < aTar.length; j++){
if(tareas[i].id_usu == aTar[j][0].id_usu){
aTar[j].length = new Array(new Date(tareas[i].fecha_registro)
,tareas[i].porcentaje);
}
}
}
}
console.info(aTar);
}
I'm using Brute-Force kind of solution, performance can always be increased.
I've created on new array above as idArray to hold the unique id_usus, and am comparing if the current tareas[i].id_usu already is there in that array, if not push the new value to aTar array and tareas[i].id_usu to idArray, else loop over the aTar array and find the array which already has the object with the current tareas[i].id_usu and push the new values at aTar[j].length.

Javascript two dimensional object array

I'm trying to define arrays of objects, I can define one dimensional array of object but as I try to define the two dimensional I get a error. What is the correct way to define a multidimensional array of objects in Javascript? Here's my code :
for(var i=0;i<3;i++)
{
obj1[i] = [
{property1},{property2}
];
for(var j=0;j<2;j++)
{
obj2[i][j]= [
{property1},{property2}
];
}
}
I think you want:
for (i=0;i<3;i++) {
f[i]=new Array();
for (j=0;j<2;j++) {
f[i][j] = appropriate property ;
}
}
Thanks for all the help, the answer is using it like this:
var obj1 = new Array();
var obj2 = new Array();
for(var i=0;i<3;i++)
{
obj1[i] = [
{property1},{property2}
];
var obj2[i] = new Array();
for(var j=0;j<2;j++)
{
obj2[i][j]= [
{property1},{property2}
];
}
}

How do I define an associative array?

I want to define what I understand is an associative array (or maybe an object) such that I have entries like the following:
"Bath" = [1,2,5,5,13,21]
"London" = [4,7,13,25]
I've tried the following:
var xref = new Object;
xref = [];
obj3 = {
offices: []
};
xref.push(obj3);
Then cycling through my data with
xref[name].offices.push(number);
But I get "TypeError: xref[name] is undefined". What am I doing wrong ?
Use an object like you do with obj3:
var xref = {};
xref.obj3 = obj3;
var name = 'obj3';
xref[name].offices.push(number);
var obj = {
arr : [],
}
var name = "vinoth";
obj.arr.push(name);
console.log(obj.arr.length);
console.log(obj.arr[0]);
obj.prop = "Vijay";
console.log(obj.prop);
You can use an object literal.
I realised that all I really wanted was a 2 dimensional array with the first dimension being the key (ie. "BATH", "LONDON") and the second being the list of cross-references (ie. 1,2,5,5,13,21) - so I don't need to understand the Object route yet ! The other suggestions may well work and be "purer" but the 2 dimensional array is easier for my old-fashioned brain to work with.
So I did the following:
var xref = [];
// go through source arrays
for (i = 0; i < offices.length; i++) {
for (j = 0; j < offices[i].rel.length; j++) {
// Check if town already exists, if not create array, then push index
if (xref[offices[i].rel[j].town] === undefined) {
xref[offices[i].rel[j].town] = [];
alert('undefined so created '+offices[i].rel[j].town);
};
xref[offices[i].rel[j].town].push(i); // Add index to town list
};
};
I believe from reading other posts that I would have problems if any of the 'offices[i].rel[j].town' were set to undefined but the data doesn't have this possibility.
Now I can access a cross-reference list by doing something like:
townlist = "";
for (i = 0; i < xref["BATH"].length; i++) {
townlist += offices[xref["BATH"][i]].name+' ';
};
alert(townlist);

Creating new object instances in a loop

I'm trying to create a new object for each item in an array by looping. The names of the objects should be based on the key of the array.
So for this array:
var arr = new Array(
"some value",
"some other value",
"a third value"
);
Would result in three objects:
alert(object1.value);
alert(object2.value);
alert(object3.value);
The code I have thus far (but isn't working) is:
// Object
function fooBar(value) {
this.value = value;
...
}
// Loop
var len = arr.length;
for (var i = 0; i < len; i++) {
var objectName = object + i;
var objectName = new fooBar(arr[i]);
}
Does what I'm asking for even make sense?
You have to make an array of the objects also
var objs = new Array();
for(var i = 0; i < len; i++) {
objs[i] = new fooBar(arr[i]);
}
alert(objs[0].value);
You can map your array:
var arr = new Array(
"some value",
"some other value",
"a third value"
);
var fooBars = arr.map(function(x) { return new fooBar(x); });
Then you can access each value:
alert(fooBars[0].value);
// etc.
or process them all at once:
fooBars.forEach(function (foo) { alert(foo.value); });
What you're asking for makes sense, but shouldn't be how you're building you JavaScript out.
Technically, there is a way of creating vars with names you build dynamically, but you shouldn't use it as it's slow, and if users are specifying what's in the array, it's unsafe and the feature is being needed in a couple of years, so your old stuff might break in future browsers.
Meanwhile, you could easily do something like:
var obj = {},
arr = [ "one", "two", "three" ],
i = 0,
len = arr.length,
val = "",
name = "";
for (; i < len; i += 1) {
name = "item" + i;
val = arr[i];
obj[name] = val;
}
Now you can call obj.item1; // "two"
If you're really desperate, you can use window as obj so when you're writing stuff in the global scope, you can just write item0; // "one" but this really isn't a great idea, for several reasons (readability, maintainability, likelihood of overwriting somebody else's properties, etc).
If you really want the variable named so, here's a solution
function fooBar(value) {
this.value = value;
}
var arr = new Array(
"some value",
"some other value",
"a third value"
);
(function(context) {
for ( var i = 0; i < arr.length; i++) {
var key = 'object' + ( i + 1 );
this[ key ] = new fooBar( arr[ i ] );
}
}(window));
alert(object1.value);
alert(object2.value);
alert(object3.value);
If you don't want global variables object1 ... just replace the keyword window with this and it will produce local variable to the current scope.
Test it out here: http://jsfiddle.net/bukart/F8ham/1/

Categories