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

1 Answer 1

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)

Sign up to request clarification or add additional context in comments.

4 Comments

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 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));
Yeah, V8 is ECMA script compatible
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));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.