🌀 Array.matrixFill()

// 🌀 Array + .matrixFill
Object.assign(Array, {
    /**
     * create an m x n matrix filled with `fill`.
     * @param {number} m number of rows
     * @param {number} n number of columns
     * @param {*} [fill=0] the value to fill with
     * @returns {[[*]]}
     */
    matrixFill(m, n, fill = 0) {
        return Array(m)
            .fill()
            .map(_ => Array(n).fill(fill));
    },
});

💈範例:

const a = [[1, 2], [4, 5]];

Array.matrixFill(2, 3)         // [ [ 0, 0, 0 ], [ 0, 0, 0 ] ]
Array.matrixFill(2, 3, '_')    // [ [ '_', '_', '_' ], [ '_', '_', '_' ] ]

Last updated