How to create a multi dimensional array in Javascript? [duplicate] - javascript

This question already has answers here:
How can I create a two dimensional array in JavaScript?
(56 answers)
Closed 9 years ago.
How do you create a multi dimensional array in Javascript using a for loop ?

var test = [];
for(var i = 0; i < 100; i++){
test.push([i, "lol"]);
}

var sDataArray = MultiDimensionalArray(2, 2);
function MultiDimensionalArray(iRows, iCols) {
var i;
var j;
var table = new Array(iRows);
for (i = 0; i < iRows; i++) {
table[i] = new Array(iCols);
for (j = 0; j < iCols; j++) {
table[i][j] = "";
}
}
return (table);
}

var arr = [];
for(var i = 0;i<100;++i){
arr[i] = [];
for(var j = 0; j < 100; ++j){
arr[i][j] = i*j;
}
}

Its an array of arrays.
var arr = [
[0,1,2],
[3,4,5],
[
['a','b','c']
]
];

Related

Initializing the 2D array elements in javascript

I want to initialize and then print the elements of a 2D array using javascript.
I wrote this code but nothing displays as output. How to output this array?
var m = 6;
var n = 3;
var mat = new Array[m][n];
for (i = 0; i < mat.length; i++) {
for (j = 0; j < mat[i].length; j++) {
mat[i][j]) = i * j;
document.writeln(mat[i][j]);
}
document.writeln("<br />");
}
<html>
<body>
</body>
<script>
var m=6;
var n=3;
var mat =new Array(m);
for( var i=0; i < m ; i++){
mat[i] = new Array(n);
for( var j=0;j< n ;j++){
mat[i][j] = i*j;
document.writeln(mat[i][j]);
}
document.writeln("<br />");
}
</script>
</html>
As BenG pointed out, you've got an extra ) but you also aren't initializing your array correctly. Javascript doesn't allow you to declare multi-dimensional arrays like other languages. Instead, you'd have to do something more like this:
var m = 6;
var n = 3;
var mat = new Array(m);
for (var i = 0; i < m; i++) {
mat[i] = new Array(n);
}
Javascript arrays are dynamic. They will grow to the size you require. You can call push() to add a new element to the array. It's also worth noting that you should avoid using the new keyword with objects and arrays. Use their literal notations [] for arrays and {} for objects. So a better solution here would be to push to the arrays as you need them.
var mat = [];
var m = 6;
var n = 3;
for (var i = 0; i < m; i++) {
// Let's add an empty array to our main array
mat.push([]);
for (var j = 0; j < n; j++) {
mat[i].push(i * j);
document.writeln(i * j);
}
document.writeln('<br />');
}

Transform multidimensional array by x value [duplicate]

This question already has answers here:
Transposing a 2D-array in JavaScript
(25 answers)
Closed 8 years ago.
If I have a large multidimensional array (matrix), how can rearange the elements so that I have "y" values as the new "x" values in the array?
Hard to explain so let me give you an example.
I want the below array.
[
[[0][1][2][3]],
[[4][5][6][7]],
[[8][9][10][11]],
[[12][13][14][15]],
]
to be transformed into the below array
[
[[0][4][8][12]],
[[1][5][9][13]],
[[2][6][10][14]],
[[3][7][11][15]],
]
for (var i = 0; i < tablesOfData.length; i++) {
for (var j = 0; j < tablesOfData[i].length; j++) {
//Transform the array
}
}
All rows needs to have the same number of columns.
If number of rows is the same as number of columns (like in your example), the following should work. If they are not the same then you need to create a n
for (var i = 0; < i tablesOfData.length; i++) {
for (var j = i; j < tablesOfData.length; j++) {
var temp = tablesOfData[i][j];
tablesOfData[i][j] = tablesOfData[j][i];
tablesOfData[j][i] = tablesOfData[i][j];
}
}
Otherwise you need to create a new table and add the values to that table, like this:
var newTable = new int[tablesOfData[i].length]();
for (var i = 0; < i tablesOfData.length; i++) {
for (var j = 0; j < tablesOfData.length; j++) {
if (i == 0)
newTable[j] = new int[tablesOfData.length]();
newTable[j][i] = tablesOfData[i][j];
}
}
I wrote the code in Notepad so it might not be the correct syntax to run on it's own but the logic should be right.

How to add array of arrays in javascript

I have a Javascript array with multiple arrays inside. I was trying to loop through the array to return an aggregated array. So far I have done following with no luck:
var a = [[1,2,3],[4,5,56],[2,5,7]];
var x = [];
for ( var i = 0; i < a.length; i++) {
for ( var j = 0; j < a[i].length; j++) {
console.log(a[i][i] = a[i][j]+a[j][i]);
}
}
I am trying to obtain the following result:
console.log(a); // -> [7,12,66]
Any suggestions or pin points where I can look for examples of similar things would be appreciated.
assuming the elements of a has the same length, the following should work
var x=[];
for(var i=0; i<a[0].length; i++){
var s = 0;
for(var j=0; j<a.length; j++){
s += a[j][i];
}
x.push(s);
}
a[0].map(function(b,i){return a.reduce(function(c,d){return c+d[i];},0);})
// [7, 12, 66]
From dc2 to dc1, try this:
var a = [[1,2,3],[4,5,56],[2,5,7]];
var x = [];
for ( var i =0; i < a.length; i++){
for ( var j = 0; j < a[i].length; j++){
x[j] = x[j] || 0;
x[j] = x[j] + a[i][j];
}
}
This worked in testing, and doesn't error with different array lengths.

Create arrays dynamically in a loop with javascript

Here's a pseudocode example about what I'm trying to do:
var totalLanguages = XX;
for(var i = 0; i < totalLanguages; i++){
var dynamicArray + i = new Array();
/*.....*/
}
I need to create dynamically many arrays as the value of totalLanguages which can be either number.
This is to be able to do something like this:
for(var i = 0; i < totalLanguages; i++){
var arrayLanguages["es"] = dynamicArray+i;
var arrayLanguages["en"] = dynamicArray+i;
}
Is there any way to do this?
var languageNames = ['en', 'es'];
var languages = {};
for (var i = 0; i < languageNames.length; i++) {
languages[languageNames[i]] = [];
}
You are basically trying to recreate an array with variable names. Just use an Array to start out!
var dynamicArray = [];
for(var i = 0; i < totalLanguages; i++) {
dynamicArray[i] = new Array();
}
You can use multi-dimensional arrays:
var languagesArray = new Array(totalLanguages);
for(var i = 0; i < totalLanguages; i++) {
var innerArray = new Array();
innerArray.push("Hello");
innerArray.push("World");
languagesArray[i] = innerArray;
}
console.log(languagesArray[0][0]);
See: How can I create a two dimensional array in JavaScript?
How about:
for(var i = 0; i < totalLanguages; i++){
window["dynamicvariable " + i] = new Array();
/*.....*/
}

Handling multidimentional array in java script is not working

function split(str)
{
var array = str.split(';');
var test[][] = new Array();
for(var i = 0; i < array.length; i++)
{
var arr = array[i].split(',');
for(var j = 0; j < arr.length; j++)
{
test[i][j]=arr[j];
}
}
}
onchange="split('1,2,3;4,5,6;7,8,9;a,b,c;d,e,f;g,h,i')"
it was not working. i need to split this string to 6*3 multi dimentional array
var array[][] = new Array() is not valid syntax for declaring arrays. Javascript arrays are one dimensional leaving you to nest them. Which means you need to insert a new array into each slot yourself before you can start appending to it.
Like this: http://jsfiddle.net/Squeegy/ShWGB/
function split(str) {
var lines = str.split(';');
var test = [];
for(var i = 0; i < lines.length; i++) {
if (typeof test[i] === 'undefined') {
test[i] = [];
}
var line = lines[i].split(',');
for(var j = 0; j < line.length; j++) {
test[i][j] = line[j];
}
}
return test;
}
console.log(split('a,b,c;d,e,f'));
var test[][] is an invalid javascript syntax.
To create a 2D array, which is an array of array, just declare your array and push arrays into it.
Something like this:
var myArr = new Array(10);
for (var i = 0; i < 10; i++) {
myArr[i] = new Array(20);
}
I'll let you apply this to your problem. Also, I don't like the name of your function, try to use something different from the standards, to avoid confusion when you read your code days or months from now.
function split(str)
{
var array = str.split(';'),
length = array.length;
for (var i = 0; i < length; i++) array[i] = array[i].split(',');
return array;
}
Here's the fiddle: http://jsfiddle.net/AbXNk/
var str='1,2,3;4,5,6;7,8,9;a,b,c;d,e,f;g,h,i';
var arr=str.split(";");
for(var i=0;i<arr.length;i++)arr[i]=arr[i].split(",");
Now arr is an array with 6 elements and each element contain array with 3 elements.
Accessing element:
alert(arr[4][2]); // letter "f" displayed

Categories

Resources