# Copying section of map array

I'm experimenting a bit with pathfinding. I'm using Javascript.

I have a map array as follows:

``````mapArray = [
[0, 0, 0, 1, 1, 0],
[1, 0, 0, 1, 0, 0],
[0, 1, 0, 1, 1, 0],
];
``````

The map is fairly excessive in size and I would like to take out a portion of it to pass to the pathfinding algo. How could I go about doing this? From the above, I could take out a section to leave this for instance:

``````mapArray = [
[0, 1, 1],
[0, 1, 0],
[0, 1, 1],
];
``````

Which would be copying from 0,2 through to 1,4 (xy).

My first thought was a for loop but it is failing for a reason I don't fully understand. Probably a misunderstanding of inserting into arrays?

``````var pathfindingMapArray = [];

for ( y = startRow; y < endRow; y++ ) {
for ( x = startColumn; x < endColumn; x++ ) {

pathfindingMapArray[y][x] = mapArray[y][x];
}
}
``````

The above fails as a TypeError.

-
If you're map is really large you will want to split it up further, basically a map of maps. Ideally those maps would be the right size for your pathfindind. And if you do a lot of pathfinding, the maps could overlap just a little so you don't have to get the next map part that often. The last bonus would of course be to store the calculated paths and try the most often used ones before calculating a new one. Your things might end up moving like ants, but maybe they are ants anyways ;-) – Thomas R. Koll Jan 1 '12 at 9:12

## 1 Answer

I tested this on jsFiddle and it seems to be working:

``````var pathfindingMapArray = [];
for (y = startRow; y < endRow; y++) {
var row = [];
for (x = startColumn; x < endColumn; x++) {
row.push(mapArray[y][x]);
}
pathfindingMapArray.push(row);
}
``````
-
Thanks. I had a d'oh! moment when I looked at your code lol. The trick was to put pathfindingMapArray[y] = [] in the row and then the [y][x]=array bit within the x for loop. – Chris Evans Jan 1 '12 at 4:48
Oh, so he creates the element automatically when passing an unused index. I'm not too familiar with Javascript, so I just googled for a push(). – David Gouveia Jan 1 '12 at 4:52
Yep, seems to be working. `mapArray.map(function(col){return col.slice(startCol, endCol);}).slice(startRow, endRow);` – David Gouveia Jan 1 '12 at 5:16
Well you could modify the pathfinding algorithm so that it also takes in the "bounds" as parameter and only processes inside that area. – David Gouveia Jan 1 '12 at 5:18
Yeah, it's 0520am over here too. :) You found a really simple solution, better than hacking at the entire algorithm! Also, be sure to run some tests on the slice/map function though, it looked okay to me when I tried it, but I might have missed some corner case. And off to bed now! – David Gouveia Jan 1 '12 at 5:29