How to Create a Two Dimensional Array in JavaScript

How can I create a two dimensional array in JavaScript?

let items = [
[1, 2],
[3, 4],
[5, 6]
];
console.log(items[0][0]); // 1
console.log(items[0][1]); // 2
console.log(items[1][0]); // 3
console.log(items[1][1]); // 4
console.log(items);

Declare an empty two-dimensional array in Javascript?

You can just declare a regular array like so:

var arry = [];

Then when you have a pair of values to add to the array, all you need to do is:

arry.push([value_1, value2]);

And yes, the first time you call arry.push, the pair of values will be placed at index 0.

From the nodejs repl:

> var arry = [];
undefined
> arry.push([1,2]);
1
> arry
[ [ 1, 2 ] ]
> arry.push([2,3]);
2
> arry
[ [ 1, 2 ], [ 2, 3 ] ]

Of course, since javascript is dynamically typed, there will be no type checker enforcing that the array remains 2 dimensional. You will have to make sure to only add pairs of coordinates and not do the following:

> arry.push(100);
3
> arry
[ [ 1, 2 ],
[ 2, 3 ],
100 ]

How can I create a two dimensional array in JavaScript?

let items = [
[1, 2],
[3, 4],
[5, 6]
];
console.log(items[0][0]); // 1
console.log(items[0][1]); // 2
console.log(items[1][0]); // 3
console.log(items[1][1]); // 4
console.log(items);

Initialize a two-dimensional array in JavaScript

You can use nested Array.from() calls:

const rows = 3

const cols = 5

const nestedArray = Array.from({ length: rows }, () =>

Array.from({ length: cols }, () => false)

);



nestedArray[0][1] = 'value'; // example of changing a single cell



console.log(nestedArray);

How can I get a two dimensional array in this format?

This is a potential answer using a recursive function. Those are quite powerful! I have added some css to style the output to make it easier to visualize.

const myList = ["red", "blue", "blue", "blue", "blue", "red", "blue", "blue", "blue", "blue", "blue", "blue", "red", "red", "red", "red", "red", "blue", "red", "red"];
const target = document.getElementById('target');

const out = ColorSplit(myList, [
[]
], 0, 0);

function ColorSplit(input, output, index, count) {
//If the value of the input is the same as the previous value, we want to add it to the currently selected array - this is determined by the index varaible.
if (count == 0 || input[count - 1] == input[count])
output[index].push(input[count]);
//If the previous value in the input is different from our current value, we want to make a new arry and add it to that. We also increment the index, as this move the pointer to the array we are currently focused on.
else {
index += 1;
output[index] = [input[count]];
}

//This is where we do the recursiveness. If we have not finished going through the entire array, we call ColorSplit again. Else we return.
return count < input.length - 1 ? ColorSplit(input, output, index, count += 1) : output;
}

//Displaying the results -- not part of the answer
for (var x = 0; x < out.length; x++) {
let comp = "<div>";
out[x].forEach(i => {
comp += `<span class="${i}">${i}</span>`;
});
comp += "</div>";
target.innerHTML += comp;
}
#target {
display: inline-flex;
flex-direction: row;
}

#target div {
display: inline-flex;
flex-direction: column;
}

span {
background-color: grey;
width: 2em;
height: 2em;
display: inline-flex;
text-align: center;
justify-content: center;
}

.red {
background-color: red;
}

.blue {
background-color: blue;
}
<div id="target"></div>

Defining 2D array Javascript

The variable leds needs to be defined as an array before it can be used as one. Then you can add elements to it using the push method; and these elements can be other (nested) arrays. For example:

//set leds as an empty array
let leds = [];

//add to the array
leds.push([]);
leds[0] = [1,2,3];

leds.push([]);
leds[1] = [4,5,6];

leds.push([7,8,9]);

//change an array value
leds[1][1] = 0;

console.log(leds);

Update two dimensional array using useState

Since it sounds like you want to effectively "iterate" through the 2-d array data I suggest keeping a "count" or some current "index" value that is incremented each update. Create a utility function that converts this "count" into a computed "row" and "column" index that you want to update.

Example:

const [count, setCount] = useState(0);
const [data, setData] = useState(Array(6).fill(Array(5).fill(null)));

const countToRowCol = (count) => {
return {
row: Math.floor(count / 5), // 5 is the inner array length
col: count % 5
};
};

const addFunc = () => {
setData((data) =>
data.map((row, i) =>
i === countToRowCol(count).row
? row.map((el, j) => (j === countToRowCol(count).col ? myValue : el))
: row
)
);
setCount((c) => c + 1);
};

addFunc is just mapping the previous state's arrays into new array references for the matching row/column index, otherwise just shallow copies the previous state.

Edit update-two-dimensional-array-using-usestate

Sample Image

2-dimensional arrays in ES6

Doing this worked for me:

var [r, c] = [5, 5]; 
var m = Array(r).fill().map(()=>Array(c).fill(0));

Basically just filling it with a dummy value so you can map over it

How to create empty 2d array in javascript?

Yes you can create an empty array and then push data into it. There is no need to define the length first in JavaScript.
Check out jsFiddle Live Demo
Define:

const arr = [[],[]];

Push data:

arr[0][2] = 'Hi Mr.A';
arr[1][3] = 'Hi Mr.B';

Read data:

alert(arr[0][2]);
alert(arr[1][3]);
Update:

Here is also a video recommended by Brady Dowling:

Create a 2D array: ([https://www.youtube.com/watch?v=tMeDkp1J2OM][2])

How can I create a two dimensional array with index and with key in javaScript?

You can not create an array with keys, because this is not the way an array works. But you can nest an object (key-value-pair) into your array.

myArray[0] = {
"S-No": 1, "Name" : "abcd", "Age": 12
};
myArray[1] = {
"S-No": 2, "Name" : "efgh", "Age": 12
};
myArray[2] = {
"S-No": 3, "Name" : "ijkl", "Age": 20
};

When you type myArray[0] JS will return the object {"S-No": 2, "Name" : "efgh", "Age": 12 }.

And you can access the object's properties easily, e.g.
myArray[0].name will return abcd.

Also you can iterate through the object's properties. Have a look at my code example.

let myArray = new Array();

myArray[0] = {
"S-No": 1, "Name" : "abcd", "Age": 12
};
myArray[1] = {
"S-No": 2, "Name" : "efgh", "Age": 12
};
myArray[2] = {
"S-No": 3, "Name" : "ijkl", "Age": 20
};

// Acesss objects
console.log('>> 1');
console.log(myArray[0])

// Access object properties
console.log('>> 2');
console.log(myArray[0].Name);

// Iterate through object properties
console.log('>> 3');
let myObject = myArray[0];
for(let key in myObject){
console.log('Key = ' + key + ' | Value = ' + myObject[key]);
}


Related Topics



Leave a reply



Submit