0

I have the following array table:

var ticket1 = [
  [0, 0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 0]
];

I want to insert values in the above array. How do I do that?

I have tried this:

ticket1[0, 0] = 20;
ticket[1, 0] = 30;
ticket[2, 0] = 40;

Expected result:

[20, 0, 0, 0, 0, 0, 0, 0, 0],
[30, 0, 0, 0, 0, 0, 0, 0, 0],
[40, 0, 0, 0, 0, 0, 0, 0, 0]

Actual result:

[20, 30, 40, 0, 0, 0, 0, 0, 0]
4
  • ticket1[0][0] = 20; You can Use this. Commented Jun 12, 2020 at 14:21
  • Welcome to Stack Overflow. You can call the index of the array and then will need to call the index of the second array. ticket1[0][0] = 20;. Commented Jun 12, 2020 at 14:22
  • thanks ozer. thanks twisty. i will try this Commented Jun 12, 2020 at 14:25
  • @ozer and #twisty both of them are correct. Their solution works! Thanks! Commented Jun 18, 2020 at 8:30

3 Answers 3

1

Consider the following example.

$(function() {
  var ticket1 = [
    [0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0]
  ];

  ticket1[0][0] = 20;
  ticket1[1][0] = 30;
  ticket1[2][0] = 40;

  $.each(ticket1, function(k, v) {
    $("<p>").html(v.join(", ")).appendTo("div");
  })
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div></div>

Reference: https://www.w3schools.com/js/js_arrays.asp

When using a Matrix, or an Array of Arrays, you still access each Array Index. So ticket1[0] will access the first element, which is an Array of Integers, so ticket1[0][0] accesses the first index of the first array.

You can make a more complex function to update / change elements in the Matrix.

Array.prototype.mPush = function(x, y, e) {
  this[x][y] = e;
  return this;
}

$(function() {
  var ticket1 = [
    [0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0]
  ];

  ticket1.mPush(0, 0, 20);
  ticket1.mPush(1, 0, 30);
  ticket1[2][0] = 40;

  $.each(ticket1, function(k, v) {
    $("<p>").html(v.join(", ")).appendTo("div");
  })
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div></div>

Sign up to request clarification or add additional context in comments.

Comments

0

function add(var){ ticket.push(var) }

Eg: ticket.push(2)

Comments

0
ticket1[0][0] = 20;

posted by ozer and twisty

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.