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);
Related
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'm working on a codecademy.com lesson on arrays. I'm supposed to write nested loops to put each card of every suit in a deck of cards in an array.
I'm really messing this up. This is one combination that I've tried that doesn't work. The only indication that I have that I'm sort of close is that it returns "52" so at least 52 objects are going into the array. can anyone point out what I'm doing wrong?
//array 1: the suits
var suits = ["clubs","hearts","diamonds","spades"];
//array 2: the ranks
var ranks = [2,3,4,5,6,7,8,9,10,"J","Q","K","A"];
//using for loops, modify the "deck" array so that it becomes a
//two-dimensional array that stores every card in the deck;
//e.g. [1, "clubs"], [2, "clubs"],etc...["A", "spades"]
var deck = [];
for(i = 0; i < suits.length; i++){
for (j = 0; j < ranks.length; j++){
var cardArray = [];
cardArray[0] = suits[i];
cardArray[0][0] = ranks[j];
deck.push(cardArray);
}
}
Each iteration, a new array is being added to deck that looks like the following:
cardArray: [ [ ranks[j] ] ]
When cardArray[0][0] is set, it is overwriting cardArray[0] as an array with index 0 containing ranks[j]. Instead, set cardArray[0] to suits, and cardArray[1] to ranks.
cardArray[0] = suits[i];
cardArray[1] = ranks[j];
deck.push(cardArray);
This results in:
for (var i = 0; i < suits.length; i++){
for (var j = 0; j < ranks.length; j++){
var cardArray = [];
cardArray[0] = suits[i];
cardArray[1] = ranks[j];
deck.push(cardArray);
}
}
You should use a var declaration for your loop counter. Your problematic code is
cardArray[0] = suits[i];
cardArray[0][0] = ranks[j];
which does things like
var foo = "clubs";
foo[0] = "J";
which obviously does not work. I think what you want is
var deck = [];
for(var i = 0; i < suits.length; i++){
var cardArray = [];
for (j = 0; j < ranks.length; j++){
var twoCards = [];
twoCards[0] = suits[i];
twoCards[1] = ranks[j];
cardArray.push(twoCards);
// // or the same thing as this loop body, shorter:
// cardArray.push([suits[i], ranks[j]]);
}
deck.push(cardArray);
}
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;
}
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