Close

February 12, 2018

One-line create 2D Matrix in Javascript

The one-line code is:

a = Array(5).fill(0).map(x => Array(10).fill(0))

“a” can be created with let, var, or const as needed.

Array(5) creates an Array with 5 items.

.fill(0) fills the 5 items with 0

.map will iterate through each of the 5 items. In this case, the .map function is taking an arrow function x => Array(10).fill(0) argument. The arrow function is read as “x” being each item of the original array (“a”) and returning into (replacing) each item of the original array with Array(10).fill(0) which is a 10 item array with each item filled with 0. So .map will change the orginal array of 5 zeros into an array with 5 arrays each of which has 10 items which are each 0. In a real-world app, the arrays would be filled with more useful objects or values.

We could use .toString() to see the array, however we don’t have to because JavaScript automatically converts Arrays to strings. For example, after the above one-line is complete “a” looks like this:

a will output all 5 items with all 10 items of each
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0

a[0] will output the items in the first item (which is an array of 10 zeros)
0,0,0,0,0,0,0,0,0,0

a[0][0] will output the item in the first item (array) of the first item (array) which is the number 0.
0

Code:
<p id=”demo”></p>
<script>
var a = Array(5).fill(0).map(x => Array(10).fill(0));
document.getElementById(“demo”).innerHTML = `a = ${a}`;
document.getElementById(“demo”).innerHTML += “<br>”;
document.getElementById(“demo”).innerHTML += `a[0] = ${a[0]}`;
document.getElementById(“demo”).innerHTML += “<br>”;
document.getElementById(“demo”).innerHTML += `a[0][0] = ${a[0][0]}`;
document.getElementById(“demo”).innerHTML += “<br>”;
document.getElementById(“demo”).innerHTML += “<br>”;
document.getElementById(“demo”).innerHTML += (typeof a) + ” is Array: ” + Array.isArray(a);
document.getElementById(“demo”).innerHTML += “<br>”;
document.getElementById(“demo”).innerHTML += (typeof a[0]) + ” is Array: ” + Array.isArray(a[0]);
document.getElementById(“demo”).innerHTML += “<br>”;
document.getElementById(“demo”).innerHTML += (typeof a[0][0]) + ” is Array: ” + Array.isArray(a[0][0]);
</script>

Results:

a = 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
a[0] = 0,0,0,0,0,0,0,0,0,0
a[0][0] = 0

object is Array: true
object is Array: true
number is Array: false

Leave a Reply

Your email address will not be published. Required fields are marked *