'Crop' a two dimensional array?
arrays, javascript, multidimensional-array
Solution
Try it this way:
crop = grid.slice(rect.x, rect.x+rect.w);
for(var i = 0; i<crop.length; i++){
crop[i] = crop[i].slice(rect.y, rect.y+rect.h);
}
Note that the dimensions of the array are now `rect.w` x `rect.h`, and all indices are negatively offset by `rect.x` and `rect.y` respectively.
Problem
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 100x100 grid. I just want to return just a crop of it, 60x60. 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