Im looking for a highly performant way to crop a two dimensional array. Consider this example:
I have a two dimensional array that makes up a 100×100 grid. I just want to return just a crop of it, 60×60. Here is an example of ‘a’ way to do it, but am looking for pointers to the most performant way of doing this.
// Settings
var gridWidth = 100;
var gridHeight = 100;
// Populate Grid
var grid = [];
for(var i = 0; i<gridWidth; i++){
grid[i] = [];
for(var j = 0; j<gridHeight; j++){
grid[i][j] = 0;
}
}
// Crop Grid
var rect = {x:20,y:20,w:60,h:60};
var crop = [];
for(var i = rect.x; i<rect.x+rect.w; i++){
crop[i-rect.x] = [];
for(var j = rect.y; j<rect.y+rect.h; j++){
crop[i-rect.x][j-rect.y] = grid[i][j];
}
}
Any thoughts greatly appreciated…
John
Try it this way:
Note that the dimensions of the array are now
rect.wxrect.h, and all indices are negatively offset byrect.xandrect.yrespectively.