LiamJC
LiamJC

Reputation: 101

Slice a 2D array into an array of smaller 'blocks' or 'chunks'

I have an issue almost exactly the one posted here, but my issue is relegated to a barebones Rhino implementation of JS, so I'm left without tools like Numpy.

I have an array which looks like this (extending an arbitrary amount down):

[[ A, B, 1, 2, α, β],
 [ C, D, 3, 4, θ, μ],
 [ E, F, 5, 6, ω, ξ]

which I'd like to slice/splice horizontally into a 'chunkified' array X elements thick; let's say I need chunks 2 elements thick:

[[[A, B],     [[1, 2],     [[α, β],
  [C, D],      [3, 4],      [θ, μ],
  [E, F]],     [5, 6]],     [ω, ξ]]]

how might I go about this?

Upvotes: 1

Views: 1370

Answers (2)

Slai
Slai

Reputation: 22876

arr = [ [ 'A', 'B', 1, 2, 'α', 'β' ],
        [ 'C', 'D', 3, 4, 'θ', 'μ' ],
        [ 'E', 'F', 5, 6, 'ω', 'ξ' ] ], l = console.log, j = JSON.stringify
        
l(j( arr[0].slice(2, 4) ))           // "[1,2]" - slice can be used to get part of array
l(j( arr.map(a => a.slice(2, 4)) ))  // "[[1,2],[3,4],[5,6]]" - map + slice to get part of each sub-array

result = [0, 2, 4].map(i => arr.map(a => a.slice(i, i+2)))  // map over the indexes to split by to get the parts

l(j( arr )), l(j( result ))

Upvotes: 4

Observer
Observer

Reputation: 3706

Try this way:

var initialArray = [[ 'A', 'B', 1, 2, 'α','β'],
                    [ 'C', 'D', 3, 4, 'θ', 'μ'],
                    [ 'E', 'F', 5, 6, 'ω', 'ξ']];
 
 function convertArray(array){
 	var convertedArray = [];
 
  var length = array.length;
 	for (var i = 0; i < length; i++){
  	var rowArray = [];
    var colArray = [];
    var innerLength = array[i].length;
    for (var j = 0; j < innerLength; j++){
   		 colArray.push(array[i][j]);
      if ((j + 1) % 2 === 0){
          rowArray.push(colArray);
          colArray = [];
      }
    	
    }  	
    convertedArray.push(rowArray);
  }
  return convertedArray;
 }
 
 var newArray = convertArray(initialArray);
 console.log(newArray)

It is a quick solution.

Upvotes: 1

Related Questions