I have a javascript object -
cell{xPos, yPos};
I would like to create a 2d array of this object.
cellPrototype = function(x, y) {
this.xPos = x;
this.yPos = y;
}
var cell = new Array();
for(var i=0;i<10;i++)
{
cell[i] = new Array();
for(var j=0;j<10;j++)
{
cell[i][j] = new cellPrototype(i,j);
}
}
This code doesn't work.
Neither does -
var cellPrototype = function(x, y) {
return {
xPos : x;
yPos : y;
}
var cell = new Array();
for(var i=0;i<10;i++)
{
cell[i] = new Array();
for(var j=0;j<10;j++)
{
cell[i][j] = new cellPrototype(i,j);
}
}
So how do I create a 2d array of an object in javascript?
This works fine for me, I'm not sure if that's exactly the output you're looking for, where
Array[x][y] will reference an object with points at x, y.
var Coords = function(x, y) {
return {
"x" : x,
"y" : y
};
};
var Main = [];
for (var i = 0, l = 10; i < l; i++) {
Main[i] = [];
for (var j = 0, l2 = 10; j < l2; j++) {
Main[i][j] = Coords(i, j);
}
}
http://jsfiddle.net/robert/d9Tgb/
You can make a 2d array like so:
var new_array = [];
var arr_length = 10;
for(var i = 0; i < arr_length; ++i){
new_array[i] = [];
}
This post is a bit old, but here is another way to create a 2D array
var arr1=[];
var x=['a','b','c','d'];
var y=[1,2,3,4];
for( var i in x){
arr1.push([x[i],y[i]]); //For x and y of the same length
}
In JavaScript x and y can be objects arrays
jsFiddle It :)
make an empty array and push the child arrays onto it
var array = [];
array.push([1,2,3,4]);
//array[0][0] == 1
or all in one shot
var array = [[1,2,3,4], [1,2,3,4], [1,2,3,4]];
Related
I'm pretty new to this field. So, currently, I want to make a simple feature for my website where if the user input like width and height value, the program will make an array that combines the two values but the other one is in alphabet form. So, for example, the user input weight = 4, and height = 2, I want the array to produce [A1, A2, B1, B2, C1, C2, D1, D2]. But, I got stuck in the part where combining those numbers and alphabet. As you can see from the snippet, I use for loop for most of the process. But, in the nested for loop, it will produce like [A1, A12, A1, A12] and so on. The alphabet is not changing and the number is stacking. I really need your help, Thank you!
var askW = prompt('Enter width value');
var askH = prompt('Enter height value');
mapGenerator(askW, askH);
function mapGenerator(askW, askH){
var w = Number(askW);
var h = Number(askH);
var containerW = [];
var containerH = [];
var initialCharValue = 64;
var i;
for (i = 64 ; i <= w + initialCharValue; i++){
containerW.push(String.fromCharCode(i));
}
for (i = 1 ; i <= h; i++){
containerH.push(i);
}
console.log(containerW);
console.log(containerH);
mapGenerator2(containerW, containerH);
function mapGenerator2(containerW, containerH){
var temparray = [];
var repeated = [];
var testArr = [];
var i,j,a,b,chunk = 1;
for (i=1,a=containerW.length; i<=a; i++) {
temparray[i] = containerW.slice(i,i+chunk);
repeated[i] = new Array(containerH.length).fill(temparray[i]).flat();
}
for (i=1, a = containerW.length; i<a ; i++){
testArr = repeated[i].map(function(item) {
for(i=1, a = containerW.length; i<a ; i++){
console.log(item+= i);
}
console.log(testArr);
});
}
}
}
P.S.: In the nested for loop, I use console.log because if I push the items into the array, it will like lagging and not logging console.
you need to create two loops that are nested the first loop will be in charge of the alphabet and the second will be in charge of the numbers like so:
function mapGenerator2(height, width) {
const result = [];
for(let i = 0; i < width; i++) {
for(let j = 1; j <= height; j++) {
result.push(`${String.fromCharCode(65 + i)}${j}`);
}
}
return result;
}
console.log(mapGenerator2(2, 4));
I have updated your MapGenerator Function which shows the correct way of using nested for loops
var askW = prompt('Enter width value');
var askH = prompt('Enter height value');
mapGenerator(askW, askH);
function mapGenerator(askW, askH){
var w = Number(askW);
var h = Number(askH);
var containerW = [];
var containerH = [];
var initialCharValue = 64;
var i;
for (i = 64 ; i <= w + initialCharValue; i++){
containerW.push(String.fromCharCode(i));
}
for (i = 1 ; i <= h; i++){
containerH.push(i);
}
result = mapGenerator2(containerW, containerH);
console.log(result)
function mapGenerator2(containerW, containerH){
var resultarray = [];
containerW.shift();
containerW.forEach(function(itemW) {
containerH.forEach(function(itemH) {
resultarray.push(itemW + itemH.toString());
})
});
return resultarray;
}
}
I want to give an array of objects two dimensions, depth and height, and then create a nested array with those dimensions. The desiredArr at the bottom would be an example of a 4 X 2.
var x = 4;
var y = 2;
var arr = [{
"key":[],
"num":Math.random()
}, //etc...];
for(var m=0; m<y; m++){
for(var n=0; n<x; n++){
//I want something like the following:
//arr[0][key][1][key][m].push( ... ) ?
arr[0]['key'].push({
"key":[],
"num":Math.random()
});
}
}
console.log(arr)
var desiredArr = [
{
'num':3,
'key':[{
'num':3.4,
'key':[{
'num':2.3,
'key':[{
'num':1.3,
'key':[{}]
}]
}]
}]
},{
'num':5,
'key':[{
'num':2.4,
'key':[{
'num':1.3,
'key':[{
'num':5.3,
'key':[{}]
}]
}]
}]
}
]
console.log(desiredArr)
https://jsfiddle.net/4yk5b7Lq/
var depth = 4;
var dim = 2;
function build(curDepth) {
if (curDepth <= 0) return {};
return {
num: Math.random(),
key: [ build(curDepth -1) ]
};
}
var nestedObj = [];
for(var i = 0; i < dim; i++) {
nestedObj.push(build(depth));
}
console.log(nestedObj);
This uses recursion to give you a more readable solution. The key portion recurses down from the starting depth until it reaches 0.
The num part can be factored to give you the number range and level of precision you want, of course.
You would need to keep a reference to the object in the deepest level of your nested array–object structure.
Something like this creates an array of length y with x nested num–key objects.
var arr = [],
x = 4,
y = 2,
obj,
tmpObj;
for (var i = 0; i < y; i++) {
obj = {};
arr.push(obj);
for (var j = 0; j < x; j++) {
obj.num = Math.random();
obj.key = [];
tmpObj = {};
obj.key.push(tmpObj);
obj = tmpObj;
}
}
console.log(arr);
I want to create multiple arrays that contain the same basic layout. Currently, i have
Array(10); //base array with moving blocks
for(var i = 0; i < 10; i++){ //creating an array within an array (2d)
base[i] = new Array(22);
}
var background = new Array(10); //background array with stationary blocks
for(var z = 0; z < 10; z++){ //same as before
background[z] = new Array(22);
}
var nextBlock = new Array(10); //next block array
for(var i = 0; i <10; i++){
nextBlock[i] = new Array(22);
}
and would like to have something similar to:
function arrayCreator(rows,cols){
var array = newArray(rows);
for(var i = 0;i < rows;i++){
array[i] = newArray(cols);
}
}
var base = arrayCreator(10,22);
var background = arrayCreator(10,22);
var nextBlock = arrayCreator(10,22);
but cant get it working. How should I approach this?
Looks like you forgot the return statement.
function arrayCreator(rows,cols){
var array = newArray(rows);
for(var i = 0;i < rows;i++){
array[i] = newArray(cols);
}
return array;
}
Sorry if this is too basic, but I am struggling at defining 4-dimensional array (of size 6x6x6x6) in JavaScript and initializing it to all 1's. What's the easiest way to do this?
Thanks!
You can use the literal syntax, but it would be very big and cumbersome. You may want to try something like this:
var x = [1, 1, 1, 1, 1, 1];
for (var i = 1; i < 4; i++) {
x = [x, x, x, x, x, x];
}
I found a slightly simpler solution:
var x = 1;
for (var i = 0; i < 4; i++) {
x = [x, x, x, x, x, x];
}
Seems like there should be easier way, but this will do it.
var array = [];
for(var i=0; i<6; i++) {
for(var j=0; j<6; j++) {
for(var k=0; k<6; k++) {
for(var l=0; l<6; l++) {
array[i][j][k][l]=1;
}
}
}
}
Edit
To generate an n-dimensional AxBxCxDx... array (untested):
Array.prototype.fill = function(elem, n) {
for(var i=0; i<n; i++, this.push(elem));
}
function generateArray() {
var dimensions = Array.prototype.slice.call(arguments);
var x = 1;
for (var i = dimensions.length-1; i >= 0; i--) {
x = [].fill(x, dimensions[i]);
}
return x;
}
to generate a 2x3x4x5 matrix:
generateArray(2,3,4,5);
I implemented ddlshack's generalized method, but ran into an issue due to the fact that arrays are "pass by reference" in JavaScript. This resulted in each dimension of the array holding multiple references to the same array rather than copies of it. To correct the issue, I implemented the solution as follows (the only other difference being that I used a second function rather than modify Array's prototype).
var fillArray = function(val, dim) {
var a = [];
for (var i = 0; i < dim; i++) {
if (Object.prototype.toString.call(val) === "[object Array]") {
val = val.slice(0);
}
a.push(val);
}
return a;
};
var generateArray = function() {
var dimensions = Array.prototype.slice.call(arguments),
val = 0;
for (var i = (dimensions.length - 1); i >= 0; i--) {
val = fillArray(val, dimensions[i]);
}
return val;
};
I am trying to create a 2 dimensional array but am getting this error.
I loop an object and try to assign them but it won't let me assign a value to the second dimension.
This is what I have:
//this is globally set
var gcollision = new Array();
function create() {
for (var X in sdata) {
X = parseInt(X);
for (var Y in sdata[X]) {
Y = parseInt(Y);
width = parseInt(sdata[X][Y][2]);
height = parseInt(sdata[X][Y][3]);
for (i = X; i != X + width; i++) {
//error occurs here "Uncaught TypeError: Cannot set property '3' of undefined"
gcollision[i][Y] = 1
for (j = Y; j != Y + height; j++) {
gcollision[X][j] = 1
}
}
}
}
How do I make it set the value of properly?
EDIT sdata looks like this:
var sdata = {"4":{"7":["1","7","3","3"]},"3":{"3":["2","8","1","1"]}};
//this is globally set
var gcollision = new Array();
function create(){
for (var X in sdata) {
X = parseInt(X);
for (var Y in sdata[X]) {
Y = parseInt(Y);
width = parseInt(sdata[X][Y][2]);
height = parseInt(sdata[X][Y][3]);
for (i=X; i!= X+width; i++) {
if( typeof gcollision[i] == 'undefined' ) gcollision[i] = new Array();
gcollision[i][Y] = 1
for (j=Y; j!=Y+height; j++) {
if( typeof gcollision[X] == 'undefined' ) gcollision[X] = new Array();
gcollision[X][j] = 1
}
}
}
}
Basically, even though you created your array, those indices do not exist yet, so you cannot reference them as arrays until after you define them as such.
If you set up your for loops a bit more optimally, you don't have to do isset and can just create the gcol[index] = Array(); the right before the inner loop where it is first accessed.
You'll need to initialize the first level of arrays, first.
function create() {
for (var X in sdata) {
X = parseInt(X);
gcollision[X] = [];
for (var Y in sdata[X]) {
Y = parseInt(Y);
width = parseInt(sdata[X][Y][2]);
height = parseInt(sdata[X][Y][3]);
for (i = X; i < X + width; i++) {
gcollision[i][Y] = 1;
for (j = Y; j < Y + height; j++) {
gcollision[X][j] = 1;
}
}
}
}