Mavematt
Mavematt

Reputation: 51

Slice/Section of two dimensional array in JavaScript

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

Upvotes: 3

Views: 11697

Answers (1)

Mark
Mark

Reputation: 92440

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)

Upvotes: 12

Related Questions