JavaScript: Faster way to create and initialize two dimensional array (matrix) JavaScript: Faster way to create and initialize two dimensional array (matrix) arrays arrays

JavaScript: Faster way to create and initialize two dimensional array (matrix)


You could use the Array.prototype.fill method:

var nodes = Array(ast.length).fill(Array(ast.length).fill(0));

jsperf test: http://jsperf.com/fill-array-matrix


Since you asked for "faster", it looks like you can gain some speed by creating a single initalized array and then using .slice() to copy it rather than initializing each array itself:

var nodes = new Array(ast.length);var copy = new Array(ast.length);for (var i = 0; i < ast.length; i++) {    copy[i] = 0;}for (var i=0; i < nodes.length; i++){    nodes[i] = copy.slice(0);}

jsperf test: http://jsperf.com/slice-vs-for-two-d-array/2

This method looks to be 10-20% faster in all three major browsers.

enter image description here


You can create array of zeros once and create copies of it:

var length = 10;var zeros = Array.apply(null, Array(length)).map(Number.prototype.valueOf, 0);var nodes = zeros.map(function(i) {    return zeros.slice();});console.log(nodes);