JavaScript updating 2d array value - javascript

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

Related

Javascript map every nth element of array

I just started to learn Javascript by my own and faced quite complex task.
I have array where are 18 labels and another 1d array where are all of the values. The label index place match every nth element in array.
E.g. if label index is 0 so then the first element and 19th element belongs to label 1 and 2th and 20th element belongs to label in index 2 .
I wrote this script that create an Object and append the values from correct index, but is there better ways to map values between two arrays?
var labelArrLenght = 18;
var i = 0, sampleArr = [];
while (i < 6642) {
sampleArr.push(i);
i++;
};
var i = 0, myObj = {};
while (i < labelArrLenght) {
myObj[i] = {label:`dummyLabel${i}`, data:[]};
i++
};
var step1 = sampleArr.length / labelArrLenght;
var stepCounter = 0;
for (var i = 0; i < step1; i++) {
for (var b = 0; b < labelArrLenght; b++) {
myObj[b]['data'].push(sampleArr[stepCounter]);
stepCounter++;
};
};
You could take a single loop approach and get the index with the remainder operator %.
var labelArrLenght = 18,
sampleArr = [],
myObj = {};
for (let i = 0; i < 90; i++) sampleArr.push(i);
for (let i = 0; i < labelArrLenght ; i++)
myObj[i] = { label: `dummyLabel${i}`, data: [] };
for (var i = 0; i < sampleArr.length; i++)
myObj[i % labelArrLenght].data.push(sampleArr[i]);
console.log(myObj);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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>

How to create 2D array and the size is given as a variable in objective-c

I'm new to objective-c. I have trouble in the 2D array. Since I have some javascript knowledge. I'll try to explain it with javascript.
var row = 10;
var col = 10;
var array[row][col];
for (var i = 0; i < row; i++){
for (var j = 0; j < col; j++){
//do something in here
}
}
row = 20;
col = 20;
for (var i = 0; i < row; i++){
for (var j = 0; j < col; j++){
//do something in here
}
}
How to code this in objective-c?
Hope this helps:
NSInteger row = 10;
NSInteger col = 10;
// Array with variable size. For fixed size, use [[NSMutableArray alloc] initWithCapacity:row]
NSMutableArray* array = [NSMutableArray new];
for (NSInteger i = 0; i < row; i++) {
// You must add values before you can access them. You cannot access a value at an index which is greater than the size of the array
NSMutableArray* colArray = [NSMutableArray new];
[array addObject:colArray];
for (NSInteger j = 0; j < col; j++) {
[colArray addObject:someObject];
// You can access the array like such:
id object = array[i][j];
// You can change an existing value in the array using the same notation:
array[i][j] = someObject;
// You cannot set an array value to nil or null. Instead use NSNull which is an object you can use to represent a null value:
array[i][j] = [NSNull null];
}
}
// You can also initialise an array with the following notation if you know the values in advance:
NSArray* anotherArray = #[objectOne, objectTwo, objectThree];
// Similarly, you can create a 2-dimensional array as follows:
NSArray* twoDimensionalArray = #[
#[rowOneColumnOne, rowOneColumnTwo, rowOneColumnThree],
#[rowTwoColumnOne, rowTwoColumnTwo, rowTwoColumnThree]
];

Iterate through an array and concatenate another array all the values before next iteration of first array?

I'm trying to build a list of Urls. The structure is like this:
http://somedomain.com/game_CATEGORY?page=NUMBER.
I have an array of game categories, ranging from action games category to word games category.
I have an array of numbers, 1 through 20.
I have pieces of the url saved as strings.
I've been trying for a day to combine them in this way:
cats = ["action","adventure","arcade","board","card","casino","casual","educational","family","music","puzzle","racing","role_playing","simulation","sports","strategy","trivia","word"],
nums = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20],
urlString1 = "http://example.com/game_",
urlString2 = "?page=",
madeUrl1 = [],
x = 1, // counter for page numbers
madeUrl2 = [];
for (var i = 0; i < cats.length; i++) {
madeUrl1.push(urlString1+cats[i]+urlString2);
};
for (var i = 0; i < madeUrl1.length; i++) {
madeUrl2.push(madeUrl1[i]+x);
x++;
};
console.log(madeUrl2);
This gets me partially there. But its printing out one number per category. I need each category printout to have ALL 20 numbers added, then move on to the next category.
You'd need to nest another for loop inside your second one. Something like:
for (var i = 0; i < madeUrl1.length; i++) {
for (int j = 0; j < nums.length; j++) {
madeUrl2.push(madeUrl1[i]+nums[j]);
}
};
That way you're iterating through the base URLs you prepared in madeUrl1, and then for each of those you're iterating through each number you have in the array.
If the numbers are simply sequential from 1 to 20, you don't even need the nums array:
for (var i = 0; i < madeUrl1.length; i++) {
for (var x = 1; x <= 20; x++) {
madeUrl2.push(madeUrl1[i]+x);
}
};
And the whole thing could be accomplished with a single nested for loop:
for (var i = 0; i < cats.length; i++) {
for (var x = 1; x <= 20; x++) {
madeUrl1.push(urlString1+cats[i]+urlString2+x);
}
};
You can use the code below:
cats = ["action","adventure","arcade","board","card","casino","casual","educational","family","music","puzzle","racing","role_playing","simulation","sports","strategy","trivia","word"],
nums = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20],
urlString1 = "http://example.com/game_",
urlString2 = "?page=",
madeUrl1 = [],
x = 1;
for (var i = 0; i < cats.length; i++) {
for (var j = 0; j < nums.length; j++) {
madeUrl1.push(urlString1+cats[i]+urlString2+nums[j]);
x++;
};
};
console.log(madeUrl1);
What we did here, is first nesting our loops. E.g., it will first loop through the first array, and when it arrives at it first item, in this case a category, it will run the nested loop 20 times, appending each number to the page. After done, it continues to the second category and so on.

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