two-dimensional javascript array

3

I have to get this structure in Javascript :

In it I will keep objects in the first column and in the second one an amount that will be a whole number. I have to create it with a two-dimensional array. I have tried a thousand ways, but something escapes me. The closest I get is this:

arrayCompras[0]=new Array();

arrayCompras[0][0]=objetoProducto;
arrayCompras[0][1]=1;

But I do not know if I go. Apart if I want to enter more data in array as I do? If I try this.

arrayCompras[1][0]=objetoProducto2;
arrayCompras[1][1]=2;

I miss an error.

  

Can not set property '0' of undefined.

Solutions?

    
asked by Carlos Rayón Álvarez 23.01.2018 в 05:57
source

4 answers

4

Cannot set property '0' of undefined. is because you did not define the array before accessing the index, as a solution you can define a array [] , and add the elements directly as type array with push

let producto = { 'nombre': 'Milk' , 'Edad' : 20};
let producto1 = { 'nombre': 'Stack' , 'Edad' : 53};

var array = [];

//añadimos dos elementos de tipo array 
array.push( [producto,  1]);
array.push( [producto1 ,  71]);


//Impresión del array antes
console.log(array[1]);
console.log("Cantidad " + array[1][1]);

//Impresión del array modificado la cantidad del segundo
// elemento , posición 1 en el array
array[1][1]=66;

// Cambios reflejados
console.log(array[1]);

console.log("Cantidad " + array[1][1]);
    
answered by 23.01.2018 / 06:36
source
5

The initialization of each array is missing with the following for you can initialize it:

for (var i = 0; i < 4; i++) {
  arrayBidimensional[i] = new Array(2);
}

and now solving your doubt:

var arrayBidimensional= new Array(4);
for (var i = 0; i < 4; i++) {
  arrayBidimensional[i] = new Array(2);
}

arrayBidimensional[0][0]="1";
arrayBidimensional[0][1]="2 ";
arrayBidimensional[1][0]="3";
arrayBidimensional[1][1]="4";

console.log("arrayBidimensional[0][0]",arrayBidimensional[0][0]);
console.log("arrayBidimensional[0][1]",arrayBidimensional[0][1]);
console.log("arrayBidimensional[1][0]",arrayBidimensional[1][0]);
console.log("arrayBidimensional[1][1]",arrayBidimensional[1][1]);
    
answered by 23.01.2018 в 06:15
3
  • Regarding the error: Can not set property '0' of undefined.

    You receive the error because when doing arrayCompras[1][0]=objetoProducto2; you have forgotten to initialize the array in position arrayCompras[1] , that is, using your code would be arrayCompras[1] = new Array() .

  • Regarding: Apart if I want to enter more data in the array as I do?

    You can use array.push

      

    The push() method adds one or more elements to the end of an array and returns the new length of the array.

Example:

var arrayCompras = [], // es equivalente a hacer new Array()
  objetoProducto = {'uno': 1},
  objetoProducto2 = {'dos': 2};

// ¿Como agregar elementos al arreglo?
arrayCompras.push([objetoProducto, 1]);
// es equivalente a:
//   arrayCompras[0][0] = objetoProducto
//   arrayCompras[0][1] = 1

arrayCompras.push([objetoProducto2, 2]);
// es equivalente a:
//   arrayCompras[1][0] = objetoProducto2
//   arrayCompras[1][1] = 2

//
console.log(arrayCompras[0][0]);
console.log(arrayCompras[0][1]);
console.log(arrayCompras[1][0]);
console.log(arrayCompras[1][1]);
    
answered by 23.01.2018 в 12:31
0

Thanks for the answers, all very correct. The issue of the problem is that at the beginning I do not know what positions the array will have, the program is based on the shopping cart that I add products and their stock. If the product already exists, checked by id, add one to the position of the quantity, if it does not exist then I believe it. In the end I solved the problem in the following way:

Carrito.prototype.insertarProducto = function (p)
{
    if (this._compras.length == 0) //Si la lista compras esta vacia la inicio con el primer producto     
    {
        this._compras = new Array();
        this._compras[0] = new Array();
        this._compras[0][0] = p;
        this._compras[0][1] = 1;
        return true;
    }

    if (this._compras.length > 0)
    {
        for (var i = 0; i < this._compras.length; i++) {
          
            if (this._compras[i][0].getId() === p.getId())//Con un for y un if compruebo si ya exite el id
            {
                this._compras[i][1] += 1;   //Si ya existe le aumento la cantidad   
                return false;
            }

        }
        
        //Si no hay id significa que no existe
        var tamaño = this._compras.length;
        this._compras[tamaño] = new Array();
        this._compras[tamaño][0] = p;
        this._compras[tamaño][1] = 1;
        return true;
    }
};

It may not be the best but it works correctly. Greetings and thanks for all the answers.

    
answered by 23.01.2018 в 15:25