Adria Fabrega
Adria Fabrega

Reputation: 11

Push one array into another array

I am a beginner student. I have an array called shoppingCart declared at the start of .js .

var shoppingCart = [];

I think this is not the most appropriate and professional way to do it, but i don't know more. And then I have the following function:

function addToShoppingCart(numProduct, quantity){
  shoppingCart.push([numProduct, quantity]);
}

With this function I want to add a new element, a two-element array, in the shoppingCart array. I've also tried to do the following:

shoppingCart.push("["+ numProduct + ", " + quantity+ "]");

I want the array looks like this:

shoppingCart = [[numProduct1,quantity1],[numProduct2,quantity2],...,[numProductN,quantityN]]

But it seems to be added as individual elements. What am I doing wrong? How should I do it correctly? Thank you for your help and/or attention.

Upvotes: 1

Views: 708

Answers (1)

Sarantis Tofas
Sarantis Tofas

Reputation: 5167

In general you should first create an object then populate and finally push it in the array:

function addToShoppingCart(numProduct, quantity){
  var product = {}
  product.number = numProduct;
  product.quantity = quantity
  shoppingCart.push(product);
  console.log(shoppingCart)
}

Now you have an array of objects as you can find out from the console.log

As @FelixKling suggested you can avoid the initialization of the empty object and just do: shoppingCart.push({number: numProduct, quantity: quantity});

Upvotes: 3

Related Questions