1

I would like to select a piece of a 2D array from a large 2D array, I know how to do this using for loops but I was wondering if there is a more effective way of achieving this.

Example:

[0,0,0,0,0,1,0]
[0,0,0,3,0,1,0]
[0,0,0,0,0,1,0]
[0,0,0,0,0,1,0]

From this array I would like to create a new array containing

[0.0.1]
[3.0.1]
[0.0.1]

So are there any better ways to create this second array than using some simple for loops?

3
  • It would be helpful if you could show the arrays in valid JavaScript format. It's a bit hard to guess what the actual structure is. Commented Aug 9, 2013 at 18:02
  • Define "more effective". For loops seem pretty effective, but then we don't know what your using this to accomplish... For example, it might be more effective to just offset every access into the original array instead. Commented Aug 9, 2013 at 18:03
  • I think I once posted a question that was almost identical to this one. I'll try to find the question that I posted, since it may be useful here. Commented Aug 9, 2013 at 19:26

1 Answer 1

1

I can't speak to the relative efficiency of this technique compared to a for loop approach, but you could leverage the javascript array's slice function for the 2nd dimension (not the first.

Array.prototype.extract2d = function extract2d( x1, y1, x2, y2 )
{
    var result = [];
    for ( var y = y1; y <= y2; y++ )
    {
        result.push( this[y].slice( x1, x2 ) );
    }
    return result;
}

Thus, you could do this:

var grid =
[
    [0,0,0,0,0,1,0],
    [0,0,0,3,0,1,0],
    [0,0,0,0,0,1,0],
    [0,0,0,0,0,1,0]
];

var subgrid = grid.extract2d( 3, 0, 5, 2 );

Do note the lack of bounds checking or verification that the sub-arrays are, in fact, sub-arrays!

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

Comments

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.