3

I need to take slice of 2d array with binary code. I need to specify where I want to start and where will be the end.

For now I have this code, but I'm pretty sure it's wrong:

var slice = [[]];
var endx = 30;
var startx = 20;
var starty = 10;
var end = 20;
for (var i = sx, a = 0; i < json_data.length, a < ex; i++, a++) {
  for (var j = sy, b = 0; j < json_data[1].length, b < ey; j++, b++)
    slice[a][b] == json_data[i][j];
}

json_data is an array in format:

[0,0,0,0,0,1,...],[1,1,0,1,1,0...],...

it is 600x600

Rick
  • 4,030
  • 9
  • 24
  • 35
Mavematt
  • 51
  • 1
  • 4

1 Answers1

12

You can do this efficiently with slice() and map().

array.slice(s, e) will take a section of an array starting at s and ending before e. So you can first slice the array and then map over the slice and slice each subarray. For example to get the section from row index 1 to 2 (inclusive) and column indexes 2 to 3 you might:

let array = [
  [1, 2, 3, 4],
  [5, 6, 7, 8],
  [9, 10, 11, 12],
  [13, 14, 15, 16]
]
let sx = 1
let ex = 2
let sy = 2
let ey = 3

let section = array.slice(sx, ex + 1).map(i => i.slice(sy, ey + 1))
console.log(section)
Mark
  • 90,562
  • 7
  • 108
  • 148
  • the code above will throw an error in Google Apps Script that should be Javascript compatible.... Why is that? Offending line `let section = array.slice(sx, ex + 1).map(i => i.slice(sy, ey + 1))`, particularly it looks like the problem lies in the `.map` function... maybe `i=> i.slice`? – Riccardo Oct 28 '19 at 16:18
  • @Riccardo works fine for me in V8. I'm doing `let sheetArr = sheet.getDataRange().getValues();` and then `let section = sheetArr.slice(start_row, end_row + 1).map(i => i.slice(start_col, end_col + 1));` – ScrapeHeap Oct 07 '20 at 19:38
  • Yeah, V8 is ECMA script compatible – Riccardo Oct 11 '20 at 07:59
  • 1
    it's very nice, but X-axis and Y-axis are mixed up, it should be: `let section = array.slice(sy, ey + 1).map(i => i.slice(sx, ex + 1));` – Shrike Jul 26 '22 at 10:14