push() a two-dimensional array - javascript
I'm trying to push to a two-dimensional array without it messing up, currently My array is:
var myArray = [
[1,1,1,1,1],
[1,1,1,1,1],
[1,1,1,1,1]
]
And my code I'm trying is:
var r = 3; //start from rows 3
var c = 5; //start from col 5
var rows = 8;
var cols = 7;
for (var i = r; i < rows; i++)
{
for (var j = c; j < cols; j++)
{
myArray[i][j].push(0);
}
}
That should result in the following:
var myArray = [
[1,1,1,1,1,0,0],
[1,1,1,1,1,0,0],
[1,1,1,1,1,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
]
But it doesn't and not sure whether this is the correct way to do it or not.
So the question is how would I accomplish this?
You have some errors in your code:
Use myArray[i].push( 0 ); to add a new column. Your code (myArray[i][j].push(0);) would work in a 3-dimensional array as it tries to add another element to an array at position [i][j].
You only expand (col-d)-many columns in all rows, even in those, which haven't been initialized yet and thus have no entries so far.
One correct, although kind of verbose version, would be the following:
var r = 3; //start from rows 3
var rows = 8;
var cols = 7;
// expand to have the correct amount or rows
for( var i=r; i<rows; i++ ) {
myArray.push( [] );
}
// expand all rows to have the correct amount of cols
for (var i = 0; i < rows; i++)
{
for (var j = myArray[i].length; j < cols; j++)
{
myArray[i].push(0);
}
}
In your case you can do that without using push at all:
var myArray = [
[1,1,1,1,1],
[1,1,1,1,1],
[1,1,1,1,1]
]
var newRows = 8;
var newCols = 7;
var item;
for (var i = 0; i < newRows; i++) {
item = myArray[i] || (myArray[i] = []);
for (var k = item.length; k < newCols; k++)
item[k] = 0;
}
You have to loop through all rows, and add the missing rows and columns. For the already existing rows, you loop from c to cols, for the new rows, first push an empty array to outer array, then loop from 0 to cols:
var r = 3; //start from rows 3
var c = 5; //start from col 5
var rows = 8;
var cols = 7;
for (var i = 0; i < rows; i++) {
var start;
if (i < r) {
start = c;
} else {
start = 0;
myArray.push([]);
}
for (var j = start; j < cols; j++) {
myArray[i].push(0);
}
}
Iterating over two dimensions means you'll need to check over two dimensions.
assuming you're starting with:
var myArray = [
[1,1,1,1,1],
[1,1,1,1,1],
[1,1,1,1,1]
]; //don't forget your semi-colons
You want to expand this two-dimensional array to become:
var myArray = [
[1,1,1,1,1,0,0],
[1,1,1,1,1,0,0],
[1,1,1,1,1,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
];
Which means you need to understand what the difference is.
Start with the outer array:
var myArray = [
[...],
[...],
[...]
];
If you want to make this array longer, you need to check that it's the correct length, and add more inner arrays to make up the difference:
var i,
rows,
myArray;
rows = 8;
myArray = [...]; //see first example above
for (i = 0; i < rows; i += 1) {
//check if the index exists in the outer array
if (!(i in myArray)) {
//if it doesn't exist, we need another array to fill
myArray.push([]);
}
}
The next step requires iterating over every column in every array, we'll build on the original code:
var i,
j,
row,
rows,
cols,
myArray;
rows = 8;
cols = 7; //adding columns in this time
myArray = [...]; //see first example above
for (i = 0; i < rows; i += 1) {
//check if the index exists in the outer array (row)
if (!(i in myArray)) {
//if it doesn't exist, we need another array to fill
myArray[i] = [];
}
row = myArray[i];
for (j = 0; j < cols; j += 1) {
//check if the index exists in the inner array (column)
if (!(i in row)) {
//if it doesn't exist, we need to fill it with `0`
row[j] = 0;
}
}
}
var r = 3; //start from rows 3
var c = 5; //start from col 5
var rows = 8;
var cols = 7;
for (var i = 0; i < rows; i++)
{
for (var j = 0; j < cols; j++)
{
if(j <= c && i <= r) {
myArray[i][j] = 1;
} else {
myArray[i][j] = 0;
}
}
}
you are calling the push() on an array element (int), where push() should be called on the array, also handling/filling the array this way makes no sense
you can do it like this
for (var i = 0; i < rows - 1; i++)
{
for (var j = c; j < cols; j++)
{
myArray[i].push(0);
}
}
for (var i = r; i < rows - 1; i++)
{
for (var j = 0; j < cols; j++)
{
col.push(0);
}
}
you can also combine the two loops using an if condition, if row < r, else if row >= r
Create am array and put inside the first, in this case i get data from JSON response
$.getJSON('/Tool/GetAllActiviesStatus/',
var dataFC = new Array();
function (data) {
for (var i = 0; i < data.Result.length; i++) {
var serie = new Array(data.Result[i].FUNCAO, data.Result[i].QT, true, true);
dataFC.push(serie);
});
The solution below uses a double loop to add data to the bottom of a 2x2 array in the Case 3. The inner loop pushes selected elements' values into a new row array. The outerloop then pushes the new row array to the bottom of an existing array (see Newbie: Add values to two-dimensional array with for loops, Google Apps Script).
In this example, I created a function that extracts a section from an existing array. The extracted section can be a row (full or partial), a column (full or partial), or a 2x2 section of the existing array. A new blank array (newArr) is filled by pushing the relevant section from the existing array (arr) into the new array.
function arraySection(arr, r1, c1, rLength, cLength) {
rowMax = arr.length;
if(isNaN(rowMax)){rowMax = 1};
colMax = arr[0].length;
if(isNaN(colMax)){colMax = 1};
var r2 = r1 + rLength - 1;
var c2 = c1 + cLength - 1;
if ((r1< 0 || r1 > r2 || r1 > rowMax || (r1 | 0) != r1) || (r2 < 0 ||
r2 > rowMax || (r2 | 0) != r2)|| (c1< 0 || c1 > c2 || c1 > colMax ||
(c1 | 0) != c1) ||(c2 < 0 || c2 > colMax || (c2 | 0) != c2)){
throw new Error(
'arraySection: invalid input')
return;
};
var newArr = [];
// Case 1: extracted section is a column array,
// all elements are in the same column
if (c1 == c2){
for (var i = r1; i <= r2; i++){
// Logger.log("arr[i][c1] for i = " + i);
// Logger.log(arr[i][c1]);
newArr.push([arr[i][c1]]);
};
};
// Case 2: extracted section is a row array,
// all elements are in the same row
if (r1 == r2 && c1 != c2){
for (var j = c1; j <= c2; j++){
newArr.push(arr[r1][j]);
};
};
// Case 3: extracted section is a 2x2 section
if (r1 != r2 && c1 != c2){
for (var i = r1; i <= r2; i++) {
rowi = [];
for (var j = c1; j <= c2; j++) {
rowi.push(arr[i][j]);
}
newArr.push(rowi)
};
};
return(newArr);
};
You can also try like this.
var r = 3; //start from rows 3
var c = 5; //start from col 5
var rows = 8;
var cols = 7;
for (var i = r; i < rows; i++)
{
for (var j = c; j < cols; j++)
{
myArray.push([var[i],var[j])
}
}
this will create a 2d array for you.
<script>
let test = new Array;
for(let i = 1; i < 10; i++){
test[i] = new Array;
test[i]['type'] = 'test-type'+i;
test[i]['content'] = 'test-content'+i;
}
console.log(test);
</script>
Related
JavaScript updating 2d array value
I'm trying to update every element of a 2d array only once. But unexpectedly array item gets update multiple times. For example: const s = "ab"; const m = [...Array(s.length).fill([...Array(s.length).fill("")])] for(let row = 0; row < s.length; row++) { for (let col = 0; col < s.length; col++) { console.log(row, col) m[row][col] += `<${row}${col}>` } } console.log(m) it should return m = [ [ '<00>', '<01>' ], [ '<10>', '<11>' ] ] but it returns m = [ [ '<00><10>', '<01><11>' ], [ '<00><10>', '<01><11>' ] ] instead. Can anyone explain it, please? Update: Here I'm looping through each item once, so there should be no chance of updating the item twice ( two value should not concat here )
Instead of initializing array with specific length. You may just initialize empty array then push the elements. Because if you do + of 2 strings, it may just concatenate it, for example: console.log("I "+"am"); Full working code: const s = "ab"; let m = []; for(let row = 0; row < s.length; row++) { m.push([]); for (let col = 0; col < s.length; col++) { m[row].push(`<${row}${col}>`); } } console.log(m);
The issue is that you are using <${row}${col}>, You should simple use let size=0 and use Array[i][j] = size++; in place of <${row}${col}> you should use the following way for 2D Arrays //Create a new 1D array let myArray = new Array(2); // Loop to create 2D array using 1D array for (let i = 0; i < myArray.length; i++) { myArray[i] = new Array(2); } //declare size let size = 0; // Loop to initialize 2D array elements. for (let i = 0; i < 2; i++) { for (let j = 0; j < 2; j++) { myArray[i][j] = size++; } } // Loop to display the elements of 2D array. for (let i = 0; i < 2; i++) { for (let j = 0; j < 2; j++) { document.write(myArray[i][j] + " "); } document.write("<br>"); }
You don't even need a loop, you can use map instead. const a = Array(2).fill(null).map( (_, row) => Array(2).fill(null).map( (_, col) => `<${row}${col}>` ) );
Push value in multi dimensional object array - Typescript [duplicate]
I'm trying to push to a two-dimensional array without it messing up, currently My array is: var myArray = [ [1,1,1,1,1], [1,1,1,1,1], [1,1,1,1,1] ] And my code I'm trying is: var r = 3; //start from rows 3 var c = 5; //start from col 5 var rows = 8; var cols = 7; for (var i = r; i < rows; i++) { for (var j = c; j < cols; j++) { myArray[i][j].push(0); } } That should result in the following: var myArray = [ [1,1,1,1,1,0,0], [1,1,1,1,1,0,0], [1,1,1,1,1,0,0], [0,0,0,0,0,0,0], [0,0,0,0,0,0,0], [0,0,0,0,0,0,0], ] But it doesn't and not sure whether this is the correct way to do it or not. So the question is how would I accomplish this?
You have some errors in your code: Use myArray[i].push( 0 ); to add a new column. Your code (myArray[i][j].push(0);) would work in a 3-dimensional array as it tries to add another element to an array at position [i][j]. You only expand (col-d)-many columns in all rows, even in those, which haven't been initialized yet and thus have no entries so far. One correct, although kind of verbose version, would be the following: var r = 3; //start from rows 3 var rows = 8; var cols = 7; // expand to have the correct amount or rows for( var i=r; i<rows; i++ ) { myArray.push( [] ); } // expand all rows to have the correct amount of cols for (var i = 0; i < rows; i++) { for (var j = myArray[i].length; j < cols; j++) { myArray[i].push(0); } }
In your case you can do that without using push at all: var myArray = [ [1,1,1,1,1], [1,1,1,1,1], [1,1,1,1,1] ] var newRows = 8; var newCols = 7; var item; for (var i = 0; i < newRows; i++) { item = myArray[i] || (myArray[i] = []); for (var k = item.length; k < newCols; k++) item[k] = 0; }
You have to loop through all rows, and add the missing rows and columns. For the already existing rows, you loop from c to cols, for the new rows, first push an empty array to outer array, then loop from 0 to cols: var r = 3; //start from rows 3 var c = 5; //start from col 5 var rows = 8; var cols = 7; for (var i = 0; i < rows; i++) { var start; if (i < r) { start = c; } else { start = 0; myArray.push([]); } for (var j = start; j < cols; j++) { myArray[i].push(0); } }
Iterating over two dimensions means you'll need to check over two dimensions. assuming you're starting with: var myArray = [ [1,1,1,1,1], [1,1,1,1,1], [1,1,1,1,1] ]; //don't forget your semi-colons You want to expand this two-dimensional array to become: var myArray = [ [1,1,1,1,1,0,0], [1,1,1,1,1,0,0], [1,1,1,1,1,0,0], [0,0,0,0,0,0,0], [0,0,0,0,0,0,0], [0,0,0,0,0,0,0], ]; Which means you need to understand what the difference is. Start with the outer array: var myArray = [ [...], [...], [...] ]; If you want to make this array longer, you need to check that it's the correct length, and add more inner arrays to make up the difference: var i, rows, myArray; rows = 8; myArray = [...]; //see first example above for (i = 0; i < rows; i += 1) { //check if the index exists in the outer array if (!(i in myArray)) { //if it doesn't exist, we need another array to fill myArray.push([]); } } The next step requires iterating over every column in every array, we'll build on the original code: var i, j, row, rows, cols, myArray; rows = 8; cols = 7; //adding columns in this time myArray = [...]; //see first example above for (i = 0; i < rows; i += 1) { //check if the index exists in the outer array (row) if (!(i in myArray)) { //if it doesn't exist, we need another array to fill myArray[i] = []; } row = myArray[i]; for (j = 0; j < cols; j += 1) { //check if the index exists in the inner array (column) if (!(i in row)) { //if it doesn't exist, we need to fill it with `0` row[j] = 0; } } }
var r = 3; //start from rows 3 var c = 5; //start from col 5 var rows = 8; var cols = 7; for (var i = 0; i < rows; i++) { for (var j = 0; j < cols; j++) { if(j <= c && i <= r) { myArray[i][j] = 1; } else { myArray[i][j] = 0; } } }
you are calling the push() on an array element (int), where push() should be called on the array, also handling/filling the array this way makes no sense you can do it like this for (var i = 0; i < rows - 1; i++) { for (var j = c; j < cols; j++) { myArray[i].push(0); } } for (var i = r; i < rows - 1; i++) { for (var j = 0; j < cols; j++) { col.push(0); } } you can also combine the two loops using an if condition, if row < r, else if row >= r
Create am array and put inside the first, in this case i get data from JSON response $.getJSON('/Tool/GetAllActiviesStatus/', var dataFC = new Array(); function (data) { for (var i = 0; i < data.Result.length; i++) { var serie = new Array(data.Result[i].FUNCAO, data.Result[i].QT, true, true); dataFC.push(serie); });
The solution below uses a double loop to add data to the bottom of a 2x2 array in the Case 3. The inner loop pushes selected elements' values into a new row array. The outerloop then pushes the new row array to the bottom of an existing array (see Newbie: Add values to two-dimensional array with for loops, Google Apps Script). In this example, I created a function that extracts a section from an existing array. The extracted section can be a row (full or partial), a column (full or partial), or a 2x2 section of the existing array. A new blank array (newArr) is filled by pushing the relevant section from the existing array (arr) into the new array. function arraySection(arr, r1, c1, rLength, cLength) { rowMax = arr.length; if(isNaN(rowMax)){rowMax = 1}; colMax = arr[0].length; if(isNaN(colMax)){colMax = 1}; var r2 = r1 + rLength - 1; var c2 = c1 + cLength - 1; if ((r1< 0 || r1 > r2 || r1 > rowMax || (r1 | 0) != r1) || (r2 < 0 || r2 > rowMax || (r2 | 0) != r2)|| (c1< 0 || c1 > c2 || c1 > colMax || (c1 | 0) != c1) ||(c2 < 0 || c2 > colMax || (c2 | 0) != c2)){ throw new Error( 'arraySection: invalid input') return; }; var newArr = []; // Case 1: extracted section is a column array, // all elements are in the same column if (c1 == c2){ for (var i = r1; i <= r2; i++){ // Logger.log("arr[i][c1] for i = " + i); // Logger.log(arr[i][c1]); newArr.push([arr[i][c1]]); }; }; // Case 2: extracted section is a row array, // all elements are in the same row if (r1 == r2 && c1 != c2){ for (var j = c1; j <= c2; j++){ newArr.push(arr[r1][j]); }; }; // Case 3: extracted section is a 2x2 section if (r1 != r2 && c1 != c2){ for (var i = r1; i <= r2; i++) { rowi = []; for (var j = c1; j <= c2; j++) { rowi.push(arr[i][j]); } newArr.push(rowi) }; }; return(newArr); };
You can also try like this. var r = 3; //start from rows 3 var c = 5; //start from col 5 var rows = 8; var cols = 7; for (var i = r; i < rows; i++) { for (var j = c; j < cols; j++) { myArray.push([var[i],var[j]) } } this will create a 2d array for you.
<script> let test = new Array; for(let i = 1; i < 10; i++){ test[i] = new Array; test[i]['type'] = 'test-type'+i; test[i]['content'] = 'test-content'+i; } console.log(test); </script>
Aligning contents of range to other range
I would like align row in function of the Name (column B & D), for exemple on the picture (1) the 2 red rectangles should be on the same line like for the 2 green rectangles but I don't know why, it doesn't work, here the code : function onOpen(event){ var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheetByName("test1"); var data = sheet.getDataRange().getValues(); for(var j = 1; j < data.length; j++) { if(data[j][1].trim() != '') { for (var i = 1; i < data.length; i++) { if(data[i][3].trim() != '') { if(data[j][1] == data[i][3]) { if(j != i) { var j1 = j + 1; var i1 = i + 1; sheet.getRange('D'+j1+':E'+j1).moveTo(sheet.getRange('F1:G1')); sheet.getRange('D'+i1+':E'+i1).moveTo(sheet.getRange('D'+j1+':E'+j1)); sheet.getRange('F1:G1').moveTo(sheet.getRange('D'+i1+':E'+i1)); } break; } } } } } } I'm pretty sure this code should work Oddly it works if I'm running the code step by step like this, firstly : for(var j = 1; j < 2; j++) after for(var j = 2; j < 3; j++) after ... until for(var j = 6; j < 7; j++)
Well I found a workaround :) function onOpen(event){ var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheetByName("test1"); var data = sheet.getDataRange().getValues(); var blank = 0; // I count the blank case so I don't run the code effortlessly on blank case for(var j = 1; j < data.length; j++) { if(data[j][1].trim() == '') blank++; } var length = data.length - blank; // I don't make a real switch in fact, I'm using a tempory space where I order the data for(var j = 1; j < length; j++) { for (var i = 1; i < length; i++) { if(data[j][1] === data[i][3]) { var j1 = j + 1; var i1 = i + 1; sheet.getRange('D'+i1+':E'+i1).moveTo(sheet.getRange('F'+j1+':G'+j1)); // column F & G is the tempory space where I put the ordered data break; } } } // I move back the tempory space ordered now to his initial place sheet.getRange('F2:G'+length).moveTo(sheet.getRange('D2:E'+length)); }
JavaScript slider puzzle - scrambling values
(I'm brand new to JS so bear with me) I am using a table to build a sliding puzzle game. I need a function that will scramble the values, but I am not sure how I should get it to display in the table cells. Right now my code just displays the numbers in order. I have two functions - one to build the table and the other to shuffle the values: var _r = 3; var _c = 3; //initializes the puzzle function newPuzzle(r, c) { var table = document.createElement("table"); table.id = "myTable"; for (var i = 0; i < r; i++) { var row = document.createElement('tr'); for (var j = 0; j < c; j++) { var column = document.createElement('td'); row.appendChild(column); } table.appendChild(row); } document.body.appendChild(table); //end of table creation //populate the table var cell = new Array(r); for (var i = 0; i < r; i++) { cell[i] = new Array(c); for (var j = 0; j < c; j++) { cell[i][j] = i*c + j; } } cell[0][0] = " "; for (var i = 0; i < cell.length; ++i) { var entry = cell[i]; for (var j = 0; j < entry.length; ++j) { var n = 0; var gridTable = document.getElementsByTagName("table"); gridTable[0].rows[i].cells[j].innerHTML = cell[i][j]; document.getElementById("myTable").rows[i].cells[j].id = "even" + (i*c+j); } } shuffle(); } function shuffle() { //declare and populate array var _array = new Array(); for (var i = 0; i <= r*c; i++) { _array[i] = i; } //shuffle tiles for (var i = 0; i <= r*c; i++) { var rand = Math.floor(Math.random() * _array.length) + i; var temp = _array[rand]; _array[rand] = _array[i]; _array[i] = temp; } //check to see if puzzle is solveable var count = 0; for (var i = 0; i <= r*c; i++) { for (var j = i; j <= r*c; j++) { if (_array[j] < _array[i]) { count++; } } } if (Math.floor(count/2) != count/2) { shuffle(); } else { for (var i = 0; i < r*c; i++) { //This is where I'm not sure what to do document.getElementsByTagName("td")[i].innerHTML = _array[i]+1; } } }
Not sure, this may help you. For solving any mathematics series below algorithm can be used. Even for some cases it will not satisfy your expected answer, but it will be correct in some other way. Steps are as below: Get difference between the numbers as shown below: Keep making difference until it seems same(difference get 0). Put the same last number which are coming same in that sequence and by adding that difference complete the series by coming up. Examples are as below: 1 2 3 4 5 6 **7** 1 1 1 1 1 **1** 1 4 9 16 25 **36** 3 5 7 9 **11** 2 2 2 **2** 1 8 27 64 125 **216** 7 19 37 61 **91** 12 18 24 **30** 6 6 **6** 0 **0** The same above algorithm is implemented in below js code. //the input var arr=[1,4,9,16]; var pa6inoArrayMelvo = function(arrr){ var nxtArr=[]; for(i=0;i<arrr.length;i++){ if(arrr[i+1] != undefined){ nxtArr.push(arrr[i+1] -arrr[i]); } } return nxtArr; } var keepArray=[]; var keepAlltheArray= function(ar){ var tempArr=[]; keepArray.push(ar); if(ar.length>1){ tempArr=pa6inoArrayMelvo(ar); keepAlltheArray(tempArr); }else{ generateArray(keepArray.length-1); console.log("ans is:"+keepArray[0]); } } var generateArray=function(idx){ if(keepArray[idx+1]){ var a=keepArray[idx+1]; var b=keepArray[idx]; var ans=a[a.length-1]+b[a.length-1]; keepArray[idx].push(ans); }else{ var ans=keepArray[idx][keepArray[idx].length-1]; keepArray[idx].push(ans); } if(idx>0){ generateArray(idx-1); } } keepAlltheArray(arr);
You need to pass your variables r and c into your shuffle function: function newPuzzle(r, c) { ... shuffle(r, c); } function shuffle(r, c) { ... if (Math.floor(count/2) != count/2) { shuffle(r, c); } } And also call newPuzzle(_r, _c); which I'm assuming you are. With just that change it works, the only problem is that is NaN in this case, you can easily fix that by checking if the value is NaN then replacing that with a space: if(isNaN(_array[i])) document.getElementsByTagName("td")[i].innerHTML = " "; Fiddle Example
Create multidimensional array in for loop
I want to create a multidimensional array like this: array[0][1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20] array[1][21,22,23,24,25,26,27....] array[.][....] How can I do this in Javascript? I have tried this: var squares = new Array(); for(var i = 1; i <= 8; i++) { for(var j = 1; j <= 20; j++) { squares.push(i, j); } } How can I accomplish this?
You can do something like this: var squares = new Array(); for(var i = 0; i <= 8; i++) { squares[i] = new Array(); for(var j = (i * 20) + 1; j <= 20 * i + 20; j++) if (squares[i] == null) squares[i] = j; else squares[i].push(j); } Output comes like: array[0][1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20] array[1][21,22,23,24,25,26,27....]
var array = []; // Main array var numArrays = 10, // Number of sub-arrays numPerArray = 20; // Number of squares per sub-array for(var i = 0; i < numArrays; i++){ var subArray = []; // Number to start at var start = i * numPerArray; // Count up to start + numPerArray for(var j = start; j < start + numPerArray; j++){ subArray.push(j); } // Add to main array array.push(subArray); }
Use modulus operand to limit the inner array's size var limit = 80 var inner_limit = 20 var square=[] var inner =[] for(var i=1;i<=limit;i++){ inner.push(i) if(i%inner_limit==0){ square.push(inner) inner = [] } }
You can do it with two "for" loops. In the first loop you go through the main array and for each element add the elements from the second loop. var arrayLength = 10; // Main array length var limit = 20; // Number of squares var array = []; for ( var i = 0; i < arrayLength; i++ ) { array[i] = []; // Create subArray for( var j = 1; j <= limit; j++ ) { array[i].push(j); } }