Create multidimensional array in for loop - javascript

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);
}
}

Related

Generate new random values and store in an array

I am trying to generate two random values and store them in an array however I would like them to be different values each time a random number between 0-3 is generated.
function new_Randomvalues(n) {
var array1 = [];
for (var i = 0; i < n; i++) {
var row = Math.round(3*Math.random());
var col = Math.round(3*Math.random());
array1.push([row,col]);
}
return array1;
}
console.log(new_Randomvalues(10));
How do I edit this function where if an array of same numbers are pushed into array1 then remove those and generate 10 unique coordinates.
Help would be appreciated thanks
Per sam's question in the comments, here's the code:
function shuffle(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
pairs = [];
for (let i = 0; i <= 3; i++) {
for (let j = 0; j <= 3; j++) {
pairs.push([i, j]);
}
}
shuffle(pairs);
pairs = pairs.slice(0, 10);
console.log(pairs);

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>

My code code infinitely and crashes the page

This is my code:
// Population
var Gene = function(text){
if(text){
this.text = text;
}
};
Gene.fitness = 0;
Gene.generation = 0;
var word = new Gene('Hello');
// This is where it crashes!!
// Make elements
var genArr = [];
var population = 20;
var mutation = 0;
for(var i = 0; i < population; i++){
var gene = "";
var abc = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var j = 0; i < word.text.length; j++) {
var element = abc.charAt(Math.floor(Math.random() * abc.length));
gene += element;
}
genArr.push(gene);
}
// Divide them - fitness
// 1/20 - 0.05% each
var fitElements = [];
for (var i = 0; i < genArr.length; i++) {
var score = 0;
var curWord = Array.from(genArr[i]);
for (var j = 0; j < word.text.length; j++) {
if(genArr[j].substr(j, 1) == word.text.substr(j, 1)){
score += 1;
}
}
if(score > 0){
fitElements.push([genArr[i], (score * (1 / population)) ** 2]);
}
}
for (var i = 0; i < fitElements.length; i++) {
console.log('Element: ' + fitElements[i][0] + ', Score: ' + fitElements[i][1]);
}
My problem is that it crashes the page but doesn't gives errors. The idea is to create a simple word register in fitElements Array but I can't see what am I missing?
Thanks in advance.
In your code the nested for loop with variable j's end condition relies on i.
Take a the line:
// VVVV it relies on i instead of j
for (var j = 0; i < word.text.length; j++) {
var element = abc.charAt(Math.floor(Math.random() * abc.length));
gene += element;
}
The new code would look something like
for (var j = 0; j < word.text.length; j++)
var element = abc.charAt(Math.floor(Math.random() * abc.length));
gene += element;
}
The only difference in the entire sample is the i is changed to a j. Cheers!

How to I run a function for each piece of an array within a for loop in Javascript?

I have this so far, trying to get it to find the sum of each one of any number of inputted numbers with integers and "-"s.
When I run this,
var howM = prompt("How many cards?")
var arr = [];
for (var i = 0; i < howM; i++)
arr.push(prompt("Enter a card:"));
console.log(arr)
var sumpre = [];
for (var i = 0; i <= howM; i++) {
var sum = 0;
var eXt = arr[i];
eXt = eXt.replace(/-/g, "");
for (i = 0; i < eXt.length; i++) {
sum += parseInt(eXt.substr(i, 1));
}
sumpre.push(sum);
}
console.log(sumpre)
I have also tried
var howM = prompt("How many cards?")
var arr = [];
for (var i = 0; i < howM; i++)
arr.push(prompt("Enter a card:"));
console.log(arr)
for (var i = 0; i < howM; i++) {
var sum = 0;
var eXt = arr[i]
eXt = eXt.replace(/-/g, "");
for (i = 0; i < eXt.length; i++) {
sum += parseInt(eXt.substr(i, 1));
}
}
console.log(sum);
In both cases I get the sum for the first piece in the array and then undefined. How do I get it to run for each piece? I kind of have an idea of what is wrong with it I just don't quite know how to fix it.
You need to use a second counter for the nested for loop, like so:
var howM = prompt("How many cards?")
var arr = [];
for(var i = 0; i < howM; i++)
arr.push(prompt("Enter a card:"));
console.log(arr)
var sumpre = [];
for(var i = 0; i < howM; i++) {
var sum = 0;
var eXt = arr[i];
eXt = eXt.replace (/-/g, "");
for (var j = 0; j < eXt.length; j++) {
sum += parseInt(eXt.substr(j, 1));
}
sumpre.push(sum);
}
console.log(sumpre)
Your var sum = 0; inside your for-loop meaning sum variable will not be accessible outside of the loop

push() a two-dimensional array

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>

Categories

Resources