Reputation: 1360
Is there a faster way to create and zero out a matrix?
Currently, my code involves two for loops:
var nodes = new Array(ast.length);
for (var i=0; i < nodes.length; i++){
nodes[i] = new Array(ast.length);
for (var j=0; j < nodes.length; j++)
nodes[i][j]=0;
}
Upvotes: 9
Views: 4470
Reputation: 1106
I don't know how fast this is in terms of producing a 2d array but it is IMHO a better way that most.
Array.prototype.dim = function(){
if( this.length==2 ){
r=this.shift(); c=this.shift();
while( r-- ) this.push( new Array( c ).fill(0,0) );
return this;
}
}
In use, the 2d array is made by initialising a regular 1d array with the parameters of x,y or rows, cols as two parameters. These are then used to dimension the array and fill it with zeros at the same time.
var arr = new Array(5,7).dim();
console.log(arr[4]);
The array then has got the desired dimension with zeros.
The output:
console.log(arr[4]);
(7) [0, 0, 0, 0, 0, 0, 0]
I hope someone finds this useful.
Upvotes: 0
Reputation: 51881
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);
Upvotes: 3
Reputation: 12027
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
Upvotes: 5
Reputation: 707606
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.
Upvotes: 3