I now multi-dimensional array in javascript is a bit silly. But in my program I have to use it.
I want to declare a dynamic 3 columns and m-rows array using javascript and then in a loop i need to insert some element to that array. finally i want to display that array.
var x = new Array();
for (var y=0; y<=counter; y++) {
x[y] = new Array (3);
x[y][0]='a';
x[y][1]='b';
x[y][2]='c';
}
your help is highly appreciated ...
arrays grow as needed and so there is no point in declaring the length of the array. what you started with is fine.
http://books.google.ca/books?id=4RChxt67lvwC&pg=PA141&lpg=PA141&dq=JS+array+grow+as+needed?&source=bl&ots=tgY8BlGXm8&sig=_3jcH1LTmYi9QiXxn9pHROpbN1s&hl=en&sa=X&ei=7v60T_XwA4ThggfGuoEX&ved=0CEoQ6AEwAQ#v=onepage&q=JS%20array%20grow%20as%20needed%3F&f=false
http://www.codingforums.com/showthread.php?t=5198
just a heads up it will create an array that is 1 bigger then counter. this is b/c in your for loop you have y<=counter and y starting at 0. if you want the length to be counter change it to
y<counter
in order to display the array you might want to consider a for nested loop.
JS
for(var i=0; i<x.length; i++)
for (var j=0; j<3; j++)
alert(x[i][j]);
where x is the reference to the array.
if you want to print the entire array at once consider creating a string from the elements in the array and print that
function displayArray(x){
var stringArray='';
for(var i=0; i<x.length; i++)
for (var j=0; j<3; j++)
stringArray+= x[i][j];
alert(stringArray);
}
Something like this?
var x = [
[
[1, 2, 3],
[4,5,6]
],
[
[7, 8, 9]
]
];
alert(x[0][1][2]);
This is one reason why JavaScript's variable syntax isn't always what it's cracked up to be. Compare to Java:
String[][][] x = new String[5][5][5];
Something like this maybe?
var sDataArray=MultiDimensionalArray(7,2);
alert(sDataArray[0][0]);
function MultiDimensionalArray(iRows,iCols)
{
var i;
var j;
var a = new Array(iRows);
for (i=0; i < iRows; i++)
{
a[i] = new Array(iCols);
for (j=0; j < iCols; j++)
{
a[i][j] = "";
}
}
return(a);
}
Being dynamic in rows maybe you want a list of arrays? You can also do a method to add a line, and increase the array size.
try something like this..
var cols = 3;
var rows = 5;
createArray(cols,rows);
function createArray(cols,rows) {
var newArray = [];
for(i=0;i<cols;i++) {
newArray[i] = [];
for(j=0;j<rows;j++) {
newArray[i][j] = "["+i+"]"+"["+j+"]";
}
}
return newArray;
}
Related
So I'm trying to create a 2d array in javascript and I'm not sure what I'm doing wrong.
Here the code I have.
var result = [];
var temp = [];
for(var i=0;i<3;i++){
temp.push(0);
}
for(var i=0;i<3;i++){
result.push(temp);
}
So this should create an array of 3x3. Now this should be the code to assign a value to only the value of the second row.
result[1][1] = 'red';
But it only results in the entire row getting changed.
[[0, 'red', 0],
[0, 'red', 0],
[0, 'red', 0]]
I tried this on my website, on codepen, even in console and its all the same. I really dont know what I'm doing wrong.
All three entries in result are references to the exact same temp array. Changes to one result in changes to the others because they are quite literally the same thing.
Instead, you'll need to create three separate array. For example:
var result = []
for (var i = 0; i < 3; i++) {
result[i] = [];
for (var j = 0; j < 3; j++) {
result[i][j] = 0;
}
}
Try replacing:
result.push(temp);
With:
result.push(temp.slice());
This will clone the temp so you won't have a reference to one and the same. temp array. Arrays are passed by reference, so they should be clonned if you prefer an independent copy.
I've to do a strange thing and I don't know if is possible.
Let assume I've one aray
MasterArray = [1,2,3,4];
Now for each MasterArray item I need to have multiple insertion, for example under the item 1 I've to push N value, for example the MasterArray[0] must have this correlations
5,8,3,9 ...
This for any items on MasterArray.
My first idea is to create a new array one for each MasterArray items, something like this
var newobject = X;
for (i = 0; i < MasterArray.length; i++) {
Arr[i] = push the newobject ;
}
But I don't think that is a good way!
The purpose it to have a kind of correlated array.
MasterArray[0] is correlated to another array [5,8,3,9, ...]
MasterArray[1] is correlated to another array [5,6,7,1, ...]
MasterArray[2] is correlated to another array [7,45,23,2, ...]
And so on
I hope to have explained myself
Just create a 2D array in this way:
var myArray = new Array(5); // For example 5;
for (var i = 0; i < myArray.length; i++) {
myArray[i] = new Array(10);
}
Or, if you don't need to specify any size:
var myArray = new Array(5); // For example 5;
for (var i = 0; i < myArray.length; i++) {
myArray[i] = [];
}
EDIT:
For manipulate you just need to use innested loops:
for (var i = 0; i < myArray.length; i++) {
for (var j = 0; i < myArray[i].length; j++) {
myArray[i][j] = x; // where x is some variable
}
For add elements in the back just use .push() method:
myArray[0].push(5);
I have the following situation in Javascript
I want the end result of the nested loop to be the following:
testArray[,[0,0,0,0],[1,1,1,1],[2,2,2,2],[3,3,3,3]]
but push doesn't seem to work nor does splice. I don't want to create any intermediate arrays because row & j are database driven and their values are actually unknown.
var testArray = [[3],[4]]; // or new Array(3,4);
for (var row=0; row< 3; row++)
{
for (var j=0; j< 4; j++)
{
testArray[j,row].push(j); //?
testArray.splice([j,row],0,j); //?
}
}
As is noted in the comments, your code does not initialize the 2-D array that you think it does. You need to create a new array and push it into the top-level array for each "row" that you require. Each sub-array can then be populated in multiple ways - up to you how you access it and "push" into them. I coded up a solution and created a Codepen for it so that you can play around with the code:
http://codepen.io/jose8a/pen/KMabNw?editors=0011
var testArray = [];
for (var row=0; row<= 3; row++)
{
testArray.push([]);
for (var j=0; j< 4; j++)
{
testArray[j, row].push(row); //?
//testArray.splice([j,row],0,j); //?
}
}
console.log(testArray);
I guess you want to push arrays to another array. This will do it.
var testArray = [ ]; //
for (var row=0; row< 3; row++) {
var tempArr = [ ];
for (var j=0; j< 4; j++){
tempArr.push(row);
}
testArray.push(tempArr);
}
There's a "new" approach to get the needed array by using ES6 Array.fill function:
var testArray = [3,4], result = [];
for (var i = 0; i < testArray[1]; i++) {
result.push([].fill.call(new Array(4), i));
}
console.log(JSON.stringify(result)); // [[0,0,0,0],[1,1,1,1],[2,2,2,2],[3,3,3,3]]
Array.prototype.fill()
I'm working on Google Script and I'm testing different ways to create two dimensions arrays.
I have created an array like this:
var codes = new Array(6);
for (var i = 0; i < 6; i++) {
codes[i] = new Array(4);
}
codes[0][0]="x";
codes[0][1]="x";
codes[0][2]="x";
codes[0][3]="x";
codes[1][0]="x";
codes[1][1]="x";
codes[1][2]="x";
codes[1][3]="x";
codes[2][0]="x";
codes[2][1]="x";
codes[2][2]="x";
codes[2][3]="x";
codes[3][0]="x";
codes[3][1]="x";
codes[3][2]="x";
codes[3][3]="x";
codes[4][0]="x";
codes[4][1]="x";
codes[4][2]="x";
codes[4][3]="x";
codes[5][0]="x";
codes[5][1]="x";
codes[5][2]="x";
codes[5][3]="x";
And it is working fine.
I read following links here, here and here.
But when I do it like this:
var codes = new Array(6);
for (var i = 0; i < 6; i++) {
codes[i] = new Array(4);
}
codes[0]=["x","x","x","x"];
codes[1]=["x","x","x","x"];
codes[2]=["x","x","x","x"];
codes[3]=["x","x","x","x"];
codes[4]=["x","x","x","x"];
codes[5]=["x","x","x","x"];
It didn't work, so I tried like this:
var codes = new Array([["x","x","x","x"],["x","x","x","x"],["x","x","x","x"],["x","x","x","x"],["x","x","x","x"],["x","x","x","x"]]);
it didn't work either.
When the code don't work, I get no error, just no display of the values.
What am I doing wrong? It looks to be the same code and the two not working ways are recommended in many documentations.
W3schools says that there is no need to use new Array().
For simplicity, readability and execution speed, use literal method ex:
var animals = ["cat", "rabbit"];
Reason why your code was not working is that you're equaling codes inside the loop and after end of loop scope 'codes' is getting only the last set array. Instead you should push those arrays to codes.
var codes = [];
for (var i = 0; i < 6; i++) {
codes.push([i]);
}
console.log(codes)
codes[0]=["x","x","x","x"];
codes[1]=["x","x","x","x"];
codes[2]=["x","x","x","x"];
codes[3]=["x","x","x","x"];
codes[4]=["x","x","x","x"];
codes[5]=["x","x","x","x"];
Better yet, two for loops to create the double array:
var codes = [], // Initiate as array, in Javascript this is actually fastre than using new (I don't know any cases you should use new)
rows = 6,
columns = 6;
for (var i = 0; i < rows; i++){
codes.push([]); // Initiate
for (var j = 0; j < columns; j++){
codes[i][j] = 'x';
}
}
Other idea, pre-initiate an array with the correct columns then copy:
var arrTemp = [],
codes = [],
rows = 6,
columns = 6;
for (var j = 0; j < columns; j++)
arrTemp[i] = 'x';
for (var i = 0; i < rows; i++)
codes.push( arrTemp.slice(0) ); // If you just push the array without slice it will make a reference to it, not copy
Other way to pre-initiate the array with 'x's:
arrTemp = Array.apply(null, Array(columns)).map(function () {return 'x'});
I have:
var array1 = [];
var array2 = [];
array1 contains 1,2
array2 contains 3,4
And I want to do this:
for(var a in array1){
for(var b in array2){
doSomething(array1[a],array2[b]);
}
}
But the problem is that function doSomething() runs twice for each array because of the two for's.
How should run it just once but with all of the arrays?
EDIT
The numbers are not in ascending order! In my real project they are ID's what can be any number in any order.
You shouldn't use for..in for looping through arrays. Use an index variable:
for (var i = 0, len = array1.length; i < len; i++) {
doSomething(array1[i], array2[i]);
}
This of course assumes they're the same length.
I think this is what you're after:
for(var i=0; i<array1.length; i++){
doSomething(array1[i],array2[i]);
}
This loops through both arrays, using the first for the length, and taking the element at the same index in both for each doSomething() call.
If you are sure that both arrays have the exact same length, you can do the following:
for (var i = 0; i < array1.length; i++) {
doSomething(array1[i], array2[i]);
}
It looks like you want to concatenate two arrays together. Use the concat() function:
var jointArray = array1.concat(array2);
for(var i=0; i < jointArray.length; i++) {
doSomething(jointArray[i]);
}
See:
http://www.w3schools.com/jsref/jsref_concat_array.asp
This if array arent same length
for (var i = 0, i < (array1.length <= array2.length ? array1.length : array2.length); i++) {
doSomething(array1[i], array2[i]);
}
DoSomething will run 4 times. If you want it to just run through the values both list together, remove the second for loop and replace b in DoSomething with a.