Skip to content
Advertisement

Creating 2d array from section of other 2d array Javascript

I am trying to cut a section of a 2d array specified by x, y and w, h. an example of an array I’m trying to cut would be

JavaScript

so if i called snapshot(2, 1, 4, 2) my desired output would be

JavaScript

So far I can cut the section and return a new array successfully but only if my Width and Height are equal.

JavaScript

an error that keeps occurring is game.js:316 Uncaught TypeError: Cannot set property '-1' of undefined

I have been going at this for a while now. I know it’s probably just some simple logic error but for some reason, I just cannot pinpoint it. Can anyone find what I’m doing wrong?

Advertisement

Answer

Using .slice allows you to pull out bits of arrays. First pull out the rows at Y -> Y + H. Next, using map() to go through each of those to slice each into the columns from X -> X + W.

You’ll need to add safe guards to avoid exceeding the size or shape of the arrays.

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement