¿Cómo puedo crear una matriz bidimensional en JavaScript?


He estado leyendo en línea y algunos lugares dicen que no es posible, algunos dicen que lo es y luego dan un ejemplo y otros refutan el ejemplo, etc.

  1. ¿Cómo declaro una matriz de 2 dimensiones en JavaScript? (suponiendo que sea posible)

  2. ¿Cómo accedería a sus miembros? (myArray[0][1] o myArray[0,1]?)

Author: royhowie, 2009-06-08

30 answers

var items = [
  [1, 2],
  [3, 4],
  [5, 6]
];
console.log(items[0][0]); // 1
console.log(items);
 1095
Author: Ballsacian1,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-10 15:20:13

Simplemente convierte cada elemento dentro del array en un array.

var x = new Array(10);

for (var i = 0; i < x.length; i++) {
  x[i] = new Array(3);
}

console.log(x);
 380
Author: Sufian,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-29 08:56:37

Similar a la respuesta de activa, aquí hay una función para crear una matriz n-dimensional:

function createArray(length) {
    var arr = new Array(length || 0),
        i = length;

    if (arguments.length > 1) {
        var args = Array.prototype.slice.call(arguments, 1);
        while(i--) arr[length-1 - i] = createArray.apply(this, args);
    }

    return arr;
}

createArray();     // [] or new Array()

createArray(2);    // new Array(2)

createArray(3, 2); // [new Array(2),
                   //  new Array(2),
                   //  new Array(2)]
 165
Author: Matthew Crumley,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-03-31 08:46:28

Javascript solo tiene matrices 1-dimensionales, pero puede construir matrices de matrices, como otros señalaron.

La siguiente función se puede utilizar para construir una matriz 2-d de dimensiones fijas:

function Create2DArray(rows) {
  var arr = [];

  for (var i=0;i<rows;i++) {
     arr[i] = [];
  }

  return arr;
}

El número de columnas no es realmente importante, porque no es necesario especificar el tamaño de un array antes de usarlo.

Entonces puedes llamar:

var arr = Create2DArray(100);

arr[50][2] = 5;
arr[70][5] = 7454;
// ...
 69
Author: Philippe Leybaert,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-06-08 18:32:00

La forma más fácil:

var myArray = [[]];
 63
Author: Fred,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-01-22 18:47:57

La razón por la que algunos dicen que no es posible es porque una matriz bidimensional es realmente solo una matriz de matrices. Los otros comentarios aquí proporcionan métodos perfectamente válidos para crear matrices bidimensionales en JavaScript, pero el punto de vista más puro sería que tienes una matriz unidimensional de objetos, cada uno de esos objetos sería una matriz unidimensional que consta de dos elementos.

Por lo tanto, esa es la causa de los puntos de vista conflictivos.

 41
Author: James Conigliaro,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-06-08 18:33:44

Pocas personas muestran el uso de push:
Para traer algo nuevo, te mostraré cómo inicializar la matriz con algún valor, ejemplo: 0 o una cadena vacía "".
Recordando que si usted tiene una matriz de 10 elementos, en javascript el último índice será 9!

function matrix( rows, cols, defaultValue){

  var arr = [];

  // Creates all lines:
  for(var i=0; i < rows; i++){

      // Creates an empty line
      arr.push([]);

      // Adds cols to the empty line:
      arr[i].push( new Array(cols));

      for(var j=0; j < cols; j++){
        // Initializes:
        arr[i][j] = defaultValue;
      }
  }

return arr;
}

Ejemplos de uso:

x = matrix( 2 , 3,''); // 2 lines, 3 cols filled with empty string
y = matrix( 10, 5, 0);// 10 lines, 5 cols filled with 0
 26
Author: Sergio Abreu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-08-08 02:22:30

Dos líneas:

var a = []; 
while(a.push([]) < 10);

Generará una matriz a de la longitud 10, llena de matrices. (Push añade un elemento a un array y devuelve la nueva longitud)

 23
Author: domenukk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-05-26 10:00:12

La respuesta más sensata parece ser

var nrows = ~~(Math.random() * 10);
var ncols = ~~(Math.random() * 10);
console.log(`rows:${nrows}`);
console.log(`cols:${ncols}`);
var matrix = new Array(nrows).fill(0).map(row => new Array(ncols).fill(0));
console.log(matrix);

Nota no podemos rellenar directamentecon las filas ya que fill utiliza un constructor de copia superficial, por lo tanto todas las filas compartirían la misma memoria...aquí hay un ejemplo que demuestra cómo cada fila sería compartida (tomada de otras respuestas):

// DON'T do this: each row in arr, is shared
var arr = Array(2).fill(Array(4));
arr[0][0] = 'foo'; // also modifies arr[1][0]
console.info(arr);
 19
Author: Francesco Dondi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-28 11:00:39

La forma más fácil:

var arr  = [];

var arr1 = ['00','01'];
var arr2 = ['10','11'];
var arr3 = ['20','21'];

arr.push(arr1);
arr.push(arr2);
arr.push(arr3);

alert(arr[0][1]); // '01'
alert(arr[1][1]); // '11'
alert(arr[2][0]); // '20'
 15
Author: Chicharito,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-12-27 13:32:45

Esto es lo que logré :

var appVar = [[]];
appVar[0][4] = "bineesh";
appVar[0][5] = "kumar";
console.log(appVar[0][4] + appVar[0][5]);
console.log(appVar);

Esto me deletreó bineeshkumar

 15
Author: Bineesh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-10 06:35:46

Cómo crear una matriz bidimensional vacía (una línea)

Array.from(Array(2), () => new Array(4))

2 y 4 son las dimensiones primera y segunda respectivamente.

Estamos haciendo uso de Array.from, que puede tomar un array como parámetro y una asignación opcional para cada uno de los elementos.

Array.de (ArrayLike [, mapFn [, thisArg]])

var arr = Array.from(Array(2), () => new Array(4));
arr[0][0] = 'foo';
console.info(arr);

El mismo truco se puede usar para Crear una matriz JavaScript que contenga 1...N


, Alternativamente, (pero más ineficiente 12% con n = 10,000)

Array(2).fill(null).map(() => Array(4))

La disminución del rendimiento viene con el hecho de que tenemos que tener los primeros valores de dimensión inicializados para ejecutar .map. Recuerde que Array no asignará las posiciones hasta que lo ordene a través de .fill o asignación directa de valores.

var arr = Array(2).fill(null).map(() => Array(4));
arr[0][0] = 'foo';
console.info(arr);

Seguimiento

¿Por qué esto no funciona?

 Array(2).fill(Array(4));

Mientras vuelve la matriz bidimensional aparentemente deseada ([ [ <4 empty items> ], [ <4 empty items> ] ]), hay una captura: los arreglos de primera dimensión han sido copiados por referencia. Eso significa que un arr[0][0] = 'foo' cambiaría dos filas en lugar de una.

var arr = Array(2).fill(Array(4));
arr[0][0] = 'foo';
console.info(arr);
console.info(arr[0][0], arr[1][0]);
 14
Author: zurfyx,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-09 22:38:54

Los arrays bidimensionales se crean de la misma manera que los arrays unidimensionales. Y se accede a ellos como array[0][1].

var arr = [1, 2, [3, 4], 5];

alert (arr[2][1]); //alerts "4"
 13
Author: tj111,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-06-08 18:27:57

No estoy seguro de si alguien ha respondido a esto, pero encontré que esto funcionó bastante bien para mí -

var array = [[,],[,]]

Eg:

var a = [[1,2],[3,4]]

Para una matriz de 2 dimensiones, por ejemplo.

 11
Author: Uchenna,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-07-01 06:50:41

Para crear una matriz 2D en JavaScript podemos crear una matriz primero y luego agregar matrices como elementos. Este método devolverá una matriz 2D con el número dado de filas y columnas.

function Create2DArray(rows,columns) {
   var x = new Array(rows);
   for (var i = 0; i < rows; i++) {
       x[i] = new Array(columns);
   }
   return x;
}

Para crear una matriz use este método como se muestra a continuación.

var array = Create2DArray(10,20);
 10
Author: prime,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-06-26 06:56:28

Use Comprensiones de matriz

En JavaScript 1.7 y superior puede usar comprensiones de matrices para crear matrices bidimensionales. También puede filtrar y / o manipular las entradas mientras llena la matriz y no tiene que usar bucles.

var rows = [1, 2, 3];
var cols = ["a", "b", "c", "d"];

var grid = [ for (r of rows) [ for (c of cols) r+c ] ];

/* 
         grid = [
            ["1a","1b","1c","1d"],
            ["2a","2b","2c","2d"],
            ["3a","3b","3c","3d"]
         ]
*/

Puede crear cualquier array n x m que desee y rellenarlo con un valor predeterminado llamando a

var default = 0;  // your 2d array will be filled with this value
var n_dim = 2;
var m_dim = 7; 

var arr = [ for (n of Array(n_dim)) [ for (m of Array(m_dim) default ]] 
/* 
         arr = [
            [0, 0, 0, 0, 0, 0, 0],
            [0, 0, 0, 0, 0, 0, 0],
         ]
*/

Se pueden encontrar más ejemplos y documentación aquí.

Tenga en cuenta que esto no es un estándar feature yet .

 8
Author: Tim Hallyburton,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-11 17:33:39

Para los amantes de un trazador de líneas Matriz.desde()

// creates 8x8 array filed with "0"    
const arr2d = Array.from({ length: 8 }, () => Array.from({ length: 8 }, () => "0"));

Otro (del comentario de dmitry_romanov) usa Array().llenar()

// creates 8x8 array filed with "0"    
const arr2d = Array(8).fill(0).map(() => Array(8).fill("0"));
 7
Author: my-,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-01 20:00:35

Mi enfoque es muy similar a la respuesta de @Bineesh, pero con un enfoque más general.

Puede declarar la matriz doble de la siguiente manera:

var myDoubleArray = [[]];

Y el almacenamiento y acceso a los contenidos de la siguiente manera:

var testArray1 = [9,8]
var testArray2 = [3,5,7,9,10]
var testArray3 = {"test":123}
var index = 0;

myDoubleArray[index++] = testArray1;
myDoubleArray[index++] = testArray2;
myDoubleArray[index++] = testArray3;

console.log(myDoubleArray[0],myDoubleArray[1][3], myDoubleArray[2]['test'],) 

Esto imprimirá la salida esperada

[ 9, 8 ] 9 123
 7
Author: Alexander,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-14 00:25:07

He encontrado a continuación es la forma más sencilla:

var array1 = [[]];   
array1[0][100] = 5; 

alert(array1[0][100]);
alert(array1.length);
alert(array1[0].length);
 5
Author: GMsoF,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-04-15 09:14:47

Tuve que hacer una función de matriz flexible para agregar "registros" a ella según lo necesitara y poder actualizarlos y hacer los cálculos que e necesitara antes de enviarlo a una base de datos para su posterior procesamiento. Aquí está el código, espero que ayude :).

function Add2List(clmn1, clmn2, clmn3) {
    aColumns.push(clmn1,clmn2,clmn3); // Creates array with "record"
    aLine.splice(aPos, 0,aColumns);  // Inserts new "record" at position aPos in main array
    aColumns = [];    // Resets temporary array
    aPos++ // Increments position not to overlap previous "records"
}

Siéntase libre de optimizar y / o señalar cualquier error:)

 4
Author: CJ Mendes,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-10-12 10:59:19

Javascript no soporta matrices bidimensionales, en su lugar almacenamos una matriz dentro de otra matriz y recuperamos los datos de esa matriz dependiendo de la posición de esa matriz a la que desea acceder. Recuerde que la numeración del array comienza en CERO .

Ejemplo De Código:

/* Two dimensional array that's 5 x 5 

       C0 C1 C2 C3 C4 
    R0[1][1][1][1][1] 
    R1[1][1][1][1][1] 
    R2[1][1][1][1][1] 
    R3[1][1][1][1][1] 
    R4[1][1][1][1][1] 
*/

var row0 = [1,1,1,1,1],
    row1 = [1,1,1,1,1],
    row2 = [1,1,1,1,1],
    row3 = [1,1,1,1,1],
    row4 = [1,1,1,1,1];

var table = [row0,row1,row2,row3,row4];
console.log(table[0][0]); // Get the first item in the array
 4
Author: Rick,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-07-30 23:53:01

Debajo de uno, crea una matriz de 5x5 y rellena con null

var md = [];
for(var i=0; i<5; i++) {
    md.push(new Array(5).fill(null));
}

console.log(md);
 4
Author: zeah,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-29 06:53:00

Aquí hay una forma rápida que he encontrado para hacer una matriz bidimensional.

function createArray(x, y) {
    return Array.apply(null, Array(x)).map(e => Array(y));
}

Puede convertir fácilmente esta función en una función ES5 también.

function createArray(x, y) {
    return Array.apply(null, Array(x)).map(function(e) {
        return Array(y);
    });
}

Por qué funciona esto: el constructor new Array(n) crea un objeto con un prototipo de Array.prototype y luego asigna el length del objeto, lo que resulta en una matriz despoblada. Debido a su falta de miembros reales no podemos ejecutar la función Array.prototype.map en él.

Sin embargo, cuando proporciona más de un argumento al constructor, como cuando si haces Array(1, 2, 3, 4), el constructor usará el objeto arguments para crear instancias y rellenar correctamente un objeto Array.

Por esta razón, podemos usar Array.apply(null, Array(x)), porque la función apply extenderá los argumentos en el constructor. Para aclarar, hacer Array.apply(null, Array(3)) es equivalente a hacer Array(null, null, null).

Ahora que hemos creado una matriz poblada real, todo lo que necesitamos hacer es llamar a map y crear la segunda capa (y).

 3
Author: dimiguel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-25 05:56:18

Puede asignar una matriz de filas, donde cada fila es una matriz de la misma longitud. O puede asignar una matriz unidimensional con elementos rows * columns y definir métodos para asignar coordenadas de fila/columna a índices de elementos.

Sea cual sea la implementación que elija, si la envuelve en un objeto, puede definir los métodos de acceso en un prototipo para que la API sea fácil de usar.

 2
Author: Nat,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-06-08 18:32:38

Encontré que este código funciona para mí:

var map = [
    []
];

mapWidth = 50;
mapHeight = 50;
fillEmptyMap(map, mapWidth, mapHeight);

...

function fillEmptyMap(array, width, height) {
    for (var x = 0; x < width; x++) {
        array[x] = [];
        for (var y = 0; y < height; y++) {

            array[x][y] = [0];
        }
    }
}
 2
Author: Fabced,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-06-14 15:46:56

Un ejemplo simplificado:

var blocks = [];

blocks[0] = [];

blocks[0][0] = 7;
 2
Author: rickatech,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-21 07:05:23

Un trazador de líneas para crear una matriz dimensional m*n 2 llena de 0.

new Array(m).fill(new Array(n).fill(0));
 2
Author: geniuscarrier,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-03 01:07:45

var playList = [
  ['I Did It My Way', 'Frank Sinatra'],
  ['Respect', 'Aretha Franklin'],
  ['Imagine', 'John Lennon'],
  ['Born to Run', 'Bruce Springsteen'],
  ['Louie Louie', 'The Kingsmen'],
  ['Maybellene', 'Chuck Berry']
];

function print(message) {
  document.write(message);
}

function printSongs( songs ) {
  var listHTML = '<ol>';
  for ( var i = 0; i < songs.length; i += 1) {
    listHTML += '<li>' + songs[i][0] + ' by ' + songs[i][1] + '</li>';
  }
  listHTML += '</ol>';
  print(listHTML);
}

printSongs(playList);
 2
Author: antelove,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-03 15:22:59

He hecho una modificación de la respuesta de Matthew Crumley para crear una función de matriz multidimensional. He agregado las dimensiones de la matriz que se pasarán como variable de matriz y habrá otra variable - value, que se utilizará para establecer los valores de los elementos de las últimas matrices en la matriz multidimensional.

/*
*   Function to create an n-dimensional array
*
*   @param array dimensions
*   @param any type value
*
*   @return array array
 */
function createArray(dimensions, value) {
    // Create new array
    var array = new Array(dimensions[0] || 0);
    var i = dimensions[0];

    // If dimensions array's length is bigger than 1
    // we start creating arrays in the array elements with recursions
    // to achieve multidimensional array
    if (dimensions.length > 1) {
        // Remove the first value from the array
        var args = Array.prototype.slice.call(dimensions, 1);
        // For each index in the created array create a new array with recursion
        while(i--) {
            array[dimensions[0]-1 - i] = createArray(args, value);
        }
    // If there is only one element left in the dimensions array
    // assign value to each of the new array's elements if value is set as param
    } else {
        if (typeof value !== 'undefined') {
            while(i--) {
                array[dimensions[0]-1 - i] = value;
            }
        }
    }

    return array;
}

createArray([]);              // [] or new Array()

createArray([2], 'empty');    // ['empty', 'empty']

createArray([3, 2], 0);       // [[0, 0],
                              //  [0, 0],
                              //  [0, 0]]
 1
Author: Hristo Enev,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:03:09

Función Recursiva para crear una matriz multidimensional:

var makeArray = function (dims, arr) {          
    if (dims[1] === undefined) {
        return new Array(dims[0]);
    }

    arr = new Array(dims[0]);

    for (var i=0; i<dims[0]; i++) {
        arr[i] = new Array(dims[1]);
        arr[i] = makeArray(dims.slice(1), arr[i]);
    }

    return arr;
}

Construir un 2x3x4x2 4D-Array:

var array = makeArray([2, 3, 4, 2]);    
 1
Author: chessweb,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-05 19:55:06