javascriptarraysmultidimensional-arrayinsertputimagedata

Insert a multidimensional array into a multidimensional array - Javascript


I have 2 multidimensional arrays. I want to insert the small array values into the larger array at a specific location.

var largeArray = [...Array(4)].map(e => Array(4).fill(0));
var smallArray = [...Array(2)].map(e => Array(2).fill(1));

Example

This is very similar to canvas context putImageData() function, where you can insert a block of values anywhere on the canvas. https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/putImageData

However, I am not using a canvas and I want to "PutSmallArray" into the large array a specific X,Y location.

How can I do this?


Solution

  • A simplistic way to achieve what you want is just to iterate over the smallArray values and indexes, using them to insert those values at the appropriate offset into largeArray:

    var largeArray = [...Array(4)].map(e => Array(4).fill(0));
    var smallArray = [...Array(2)].map(e => Array(2).fill(1));
    
    function insertArray(big, small, x, y) {
      small.forEach((a, i) => a.forEach((v, j) => big[y + i][x + j] = v));
      return big;
    }
    
    console.log(insertArray(largeArray, smallArray, 1, 1));

    Note that this code doesn't check whether smallArray fits inside largeArray at the x,y coordinates specified. If that might not be the case, then dependent on the result you desire (an unmodified array or only the elements that fit modified), you will need to check whether the indexes fall outside the bounds of largeArray e.g.

    var largeArray = [...Array(4)].map(e => Array(4).fill(0));
    var smallArray = [...Array(2)].map(e => Array(2).fill(1));
    
    // don't update unless the array fits perfectly
    function insertArray(big, small, x, y) {
      if (small.length + y > largeArray.length ||
          small[0].length + x > largeArray[0].length)
          return big;
      small.forEach((a, i) => a.forEach((v, j) => big[y + i][x + j] = v));
      return big;
    }
    
    console.log(insertArray(largeArray, smallArray, 3, 1));