Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 523
Mavematt Avatar asked Dec 16 '25 12:12

Mavematt


1 Answers

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)
like image 193
Mark Avatar answered Dec 19 '25 02:12

Mark



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!