Nik Hendricks
Nik Hendricks

Reputation: 294

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


var arr = [
            ['0', '1', 'd', 'a', '1', '1'],
            ['0', 's', '0', 'f', 's', 'g'],
            ['b', 'x', 'e', '0', 'v', 'a'],
            ['a', 'e', 'n', '0', 'z', 'm'],
            ['b', 'x', 'e', '0', 'v', 'a'],
         ];

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

var retarr = [
                 ['0', 'f', 's', 'g'],
                 ['e', '0', 'v', 'a'],
             ]

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

snapshot(x, y, w, h){
    var retgrid = new Grid(w, h); 
    var startX = x;
    var startY = y;
    var endX = x + w;
    var endY = y + h;
    console.log(`x: ${x} y: ${y}`)
    console.log(`w: ${w} h: ${h}`)

    for(var i = startY; i < endY; i++){
        for(var j = startX; j < endX; j++){
           // console.log(retgrid)
            retgrid[j - startX][i - startY] = this.grid[j][i]
        }
    }
    console.log(retgrid)
    return retgrid;
}

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?

Upvotes: 0

Views: 95

Answers (3)

Siva Kondapi Venkata
Siva Kondapi Venkata

Reputation: 11001

First filter out unwanted rows and use map and slice

const snapshot = (arr, x, y, w, h) =>
  arr
    .filter((_, i) => i >= y && i < y + h)
    .map((items) => items.slice(x, x + w));

var arr = [
  ["0", "1", "d", "a", "1", "1"],
  ["0", "s", "0", "f", "s", "g"],
  ["b", "x", "e", "0", "v", "a"],
  ["a", "e", "n", "0", "z", "m"],
  ["b", "x", "e", "0", "v", "a"],
];

console.log(snapshot(arr, 2, 1, 4, 2));

Upvotes: 1

terrymorse
terrymorse

Reputation: 7086

This task can be simplified greatly by breaking it up into two steps:

Step 1: extract the desired complete rows

Step 2: extract the desired columns from the extracted rows.

const arr = [
  ['0', '1', 'd', 'a', '1', '1'],
  ['0', 's', '0', 'f', 's', 'g'],
  ['b', 'x', 'e', '0', 'v', 'a'],
  ['a', 'e', 'n', '0', 'z', 'm'],
  ['b', 'x', 'e', '0', 'v', 'a'],
];

function snapshot (array, colStart, rowStart, cols, rows) {
  
  // slice out the rows
  const fullRows = array.slice(rowStart, rowStart+rows);
  console.log('fullRows:', fullRows);
  
  // cut down the rows
  const cutRows = fullRows.map(row => row.slice(colStart, colStart+cols));
  return cutRows;
}

const result = snapshot(arr, 2, 1, 4, 2);
console.log('result:', result);

Upvotes: 1

Randy Casburn
Randy Casburn

Reputation: 14165

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.

var arr = [
  ['0', '1', 'd', 'a', '1', '1'],
  ['0', 's', '0', 'f', 's', 'g'],
  ['b', 'x', 'e', '0', 'v', 'a'],
  ['a', 'e', 'n', '0', 'z', 'm'],
  ['b', 'x', 'e', '0', 'v', 'a'],
];

console.log(snapshot(2, 1, 4, 2));

function snapshot(x, y, w, h) {
  return arr.slice(y, y + h).map(a => a.slice(x, x + w))
}

Upvotes: 1

Related Questions