简体   繁体   中英

create a matrix of objects with x y coordinates within arrays in vanilla JavaScript

I'm trying to create a matrix of objects with x, y coordinates.

For example:

 var simpleMatrix = [ [{x: 0, y: 0}, {x: 0, y: 1}], [{x: 1, y: 0}, {x: 1, y: 1}], ] console.log('simpleMatrix is: ', simpleMatrix) 

How do I abstract this into a function so I can generate a bigger grid? For example, a grid with 10 rows by 10 columns (or 5 rows by 6 columns, or whatever).

I want an array of objects that each contain their own coordinates.

You can chain two Array.from s together to build nested arrays from scratch:

 const makeMatrix = (lengthX, lengthY) => ( Array.from( { length: lengthY }, (_, y) => Array.from( { length: lengthX }, (_, x) => ({ x, y }) ) ) ); console.log(makeMatrix(2, 2)); console.log(makeMatrix(3, 1)); 

The first argument to Array.from is an object that the interpreter attempts to turn into an array. Passing an object with a length property will create an array of that length with undefined values. Then, the second argument to Array.from is an optional mapping function, the same as Array.prototype.map - here, we can exploit that by using the second argument to .map , which is the current index being iterated over.

So, with the outer Array.from 's getting the y coordinate from the mapper, and the inner Array.from getting the x coordinate from the mapper, we can then return an object with the desired coordinates from the inner function, which will create the grid.

var inputCoord = [];
var matrix;

function initMatrix( rows, cols ) {

    var index = 0;
    var aMatrix = [];
    for( var x = 0; x < rows; x++ ) {

        var aRow = [];
        for( var y = index; y < inputCoord.length; y++ ) {

            aCol.push( inputCoord[ y ] );

            if( y == ( cols - 1 ) ) {
                index += cols;
                break;
            }
        }

        aMatrix.push( aRow );

    }

    return aMatrix;

}

inputCoord.push( { x: 0, y: 1 } );
inputCoord.push( { x: 0, y: 1 } );
inputCoord.push( { x: 0, y: 1 } );
inputCoord.push( { x: 0, y: 1 } );
inputCoord.push( { x: 0, y: 1 } );  
inputCoord.push( { x: 0, y: 1 } );

matrix = initMatrix( 2, 3 ); //rows * cols have to always be equal to inputCoord.length

I didn't try the code, but something like this should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM