How to create a multidimensional array in JavaScript? - javascript

How can I create a multidimensional array in JavaScript?
I have:
var m = 4;
for (var i = 0; i < m; i++){
groupsData.name_of_bar = [];
groupsData.name_of_bar[i]['a'] = data[i].a;
groupsData.name_of_bar[i]['ab'] = data[i].ab;
groupsData.name_of_bar[i]['de'] = data[i].de;
groupsData.name_of_bar[i]['gh'] = data[i].gh;
groupsData.name_of_bar[i]['xy'] = data[i].xy;
}
If I do:
groupsData.name_of_bar[0]
I get errors:
TypeError: Cannot read property '0' of undefined
TypeError: Cannot set property 'a' of undefined
What am I doing wrong?

JavaScript doesn't support multidimensional arrays per se. The closest you can come is to create an array where the values in it are also arrays.
// Set this **outside** the loop so you don't overwrite it each time you go around the loop
groupsData.name_of_bar = [];
for (var i = 0; i < m; i++){
// Create a new "array" each time you go around the loop
// Use objects, not arrays, when you have named properties (instead of ordered numeric ones)
groupsData.name_of_bar[i] = {};
groupsData.name_of_bar[i]['a'] = data[i].a;
groupsData.name_of_bar[i]['ab'] = data[i].ab;
groupsData.name_of_bar[i]['de'] = data[i].de;
groupsData.name_of_bar[i]['gh'] = data[i].gh;
groupsData.name_of_bar[i]['xy'] = data[i].xy;
}

Each iteration through the loop, you are doing groupsData.name_of_bar = [];. This removes whatever else is already in there and replaces it with a blank array.
Also, when you do groupsData.name_of_bar[i]['a'], you need to create groupsData.name_of_bar[i] first.
A way to do this is:
groupsData.name_of_bar = [];
var m = 4;
for (var i = 0; i < m; i++){
groupsData.name_of_bar.push({
a: data[i].a,
ab: data[i].ab,
ab: data[i].ab,
de: data[i].de,
gh: data[i].gh,
xy: data[i].xy,
});
}
Note that in JavaScript, arrays can only be numerically indexed. If you want string indexes, you need to use an object.
Also, if there are no other values in data[i], then you can simplify this even further by doing:
groupsData.name_of_bar = [];
var m = 4;
for (var i = 0; i < m; i++){
groupsData.name_of_bar.push(data[i]);
}
Heck, why not just use groupsData.name_of_bar = data; and lose the loop altogether?

The way you are declaring your objects are a little off. It looks like you are attempting to create an array of objects.
var groupsData = {name_of_bar: []},
m = 4,
i = 0;
for(; i < m; i++) {
groupsData.name_of_bar.push({
a: data[i].a,
ab: data[i].ab,
de: data[i].de,
gh: data[i].gh,
xy = data[i].xy
});
}

Related

Two dimensional arrays populating does not work javascript

When i try to create two dimensional array in javascript using loop, it gives me following error:
Cannot set property 'indexis' of undefined
Code:
var indexes = [];
for (var i = 0; i < headingsArray.length; i++) {
if (headingsArray[i].toLowerCase().indexOf('name') != -1) {
indexes[i]['indexis'] = i;
indexes[i]['headingis'] = headingsArray[i]; //assuming headingsArray exist
indexes[i]['valueis'] = rows[0][i]; //assuming rows exist
}
}
You need to create the inner arrays/objects as well, or else index[i] is undefined, so index[i]['indexis'] will throw an exception.
var indexes = [];
for (var i = 0; i < headingsArray.length; i++) {
indexes[i] = {}; //<---- need this
if (headingsArray[i].toLowerCase().indexOf('name') != -1) {
indexes[i]['indexis'] = i;
indexes[i]['headingis'] = headingsArray[i];
indexes[i]['valueis'] = rows[0][i];
}
}
You described it as a multidimensional array, but you're using it as though it's an array of objects (because you're accessing named properties, instead of numbered properties). So my example code is creating objects on each iteration. If you meant to have an array of arrays, then do indexes[i] = [], and interact with things like indexes[i][0] rather than indexes[i]['indexis']
You need an object before accessing a property of it.
indexes[i] = indexes[i] || {}
indexes[i]['indexis'] = i;
define temp var with field initialise to null & use push() function of JavaScript
for (var i = 0; i < headingsArray.length; i++) {
var temp={indexis: null,headingis:null,valueis:null};;
if (headingsArray) {
temp['indexis'] = i;
temp['headingis'] = headingsArray[i]; //assuming headingsArray exist
temp['valueis'] = rows[0][i];
indexes.push(temp);
}
}

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.

jQuery iterate through loop delete elements

I have a javascript array of objects: each object contains key/value pairs. I'm trying to iterate through this array, and delete any object whose value for a particular key (say "Industry") fails to match a given value. Here is my code, for some reason it's not looping through the whole array, and I think it has something to do with the fact that when I delete an item the loop counter is botched somehow:
var industry = 'testing';
var i = 0;
for (i = 0; i < assets_results.length; i++) {
var asset = assets_results[i];
var asset_industry = asset['industry'];
if (industry != asset_industry) { assets_results.splice(i,1); }
}
Any ideas? Thanks in advance.
This is because when you splice one element, the size of array decreases by one. All elements after the splice shift one position to the beginning of the array and fills the space of spliced one. So the code misses one element.Try this code.
var industry = 'testing';
var i = 0;
for (i = 0; i < assets_results.length; i++) {
var asset = assets_results[i];
var asset_industry = asset['industry'];
if (industry != asset_industry) {
assets_results.splice(i,1);
i--;
}
}
This is a common problem when modifying an object while iterating through it. The best way to avoid this problem is, rather than deleting pairs from the existing array if they fail the test, to create a new array and only add pairs if they pass the test.
var industry = 'testing';
var i = 0;
var asset_results_filtered = [];
for (i = 0; i < assets_results.length; i++) {
if (industry == assets_results[i]) {
asset_results_filtered.push(assets_results[i]);
}
}
EDIT: Your code looked a bit illogical — I modified the example to use the variables given.
splice removes an element from an array and resizes it :
var arra = ['A', 'B', 'C', 'D'];
arr.splice(1,2); // -> ['A', 'D'];
Which means that you should not increment i when you splice, because you skip the next element. splicing will make of the i + 2 element the i + 1 element.
var industry = 'testing';
for (var i = 0, max = assets_results.length; i < max; ) { // Accessing a property is expensive.
if (industry != assets_results[i]['industry']) {
assets_results.splice(i,1);
} else {
++i;
}
}
Try this instead:
var industry = 'testing';
var i = assets_results.length - 1;
for (; i > 0; i--) {
var asset = assets_results[i],
asset_industry = asset['industry'];
if (industry != asset_industry) { assets_results.splice(i,1); }
}

How to create an array like this in JavaScript?

I want to create an array like this:
s1 = [[[2011-12-02, 3],[2011-12-05,3],[5,13.1],[2011-12-07,2]]];
How to create it using a for loop? I have another array that contains the values as
2011-12-02,3,2011-12-05,3,2011-12-07,2
One of possible solutions:
var input = ['2011-12-02',3,'2011-12-05',3,'2011-12-07',2]
//or: var input = '2011-12-02,3,2011-12-05,3,2011-12-07,2'.split(",");
var output = [];
for(i = 0; i < input.length; i += 2) {
output.push([t[i], t[i + 1]])
}
If your values always come in pairs:
var str = '2011-12-02,3,2011-12-05,3,2011-12-07,2',//if you start with a string then you can split it into an array by the commas
arr = str.split(','),
len = arr.length,
out = [];
for (var i = 0; i < len; i+=2) {
out.push([[arr[i]], arr[(i + 1)]]);
}
The out variable is an array in the format you requested.
Here is a jsfiddle: http://jsfiddle.net/Hj6Eh/
var s1 = [];
for (x = 0, y = something.length; x < y; x++) {
var arr = [];
arr[0] = something[x].date;
arr[1] = something[x].otherVal;
s1.push(arr);
}
I've guessed here that the date and the other numerical value are properties of some other object, but that needn't be the case...
I think you want to create an array which holds a set of arrays.
var myArray = [];
for(var i=0; i<100;i++){
myArray.push([2011-12-02, 3]); // The values inside push should be dynamic as per your requirement
}

declaring more than 10 objects

as we know we can declare an array like this
for (int i=0;i<array.length;i++)
{ d[i]=new array();}
What about an object I want to declare more than 10 objects and I think it's not efficient to
write a declare statements for 10 times !!like this
car c1 = new car();
car c2= new Car();
..etc
what can I do ?
You are mixing the things a little.
var array = [];
for (var i = 0; i < 10; i++)
{
array[i] = new Car();
}
As Daniel noted, you can even use Array.push() in this way:
var array = [];
for (var i = 0; i < 10; i++)
{
array.push(new Car());
}
The point is that you declare the array with var array = [] (or with var array = new Array(), see the differences here What’s the difference between "Array()" and "[]" while declaring a JavaScript array?) and you set the items at the index you want (in Javascript arrays are dynamicly sized)
Use an array of objects like:
var cars = [];
for (var i = 0; i < 10; i++) {
cars.push(new Car());
}
Hum, what you're doing in your first example is declaring an array of array. To create an array, simply do
var a = [];
To create and maintain many objects, put them in that array:
for(var i = 0; i < 10; i++)
a[i] = new Car();
car[0].drive(); //Drive first car
You can:
use eval (it was designed for things like this)
use an array of objects
for (var i=1,n=3; i<n; i++)
eval("c" + i + "= new Car()");
var a = [];
for (var i=1,n=3; i<n; i++)
a[i] = new Car();

Categories