0

How to get the cell value in 2D array in Javascript

I have a table of numbers, which will 31 cols * 9 rows, I want to get the cell value from getting the spot function! so I want [1][2].the important value for me is Y only? how to pass theGrid to the spot function? also, any suggestions for performance will be fantastic as you can see the it is huge array

    var cols = 31;
    var rows = 9; 
    var theGrid = new Array(cols);
    var i;
    var j;
    //get the spot
    function getTheSpot(j, i) {
      // when the col met the row it create a spot
      //that what i need to get 
        this.y = i;
        this.x = j;
        return i;
        return j;
    }

    //create a grid for the numbers 
    function createGrid() {
        // BELOW CREATES THE 2D ARRAY 
       for (var i = 0; i < cols; i++) {
           theGrid[i] = new Array(rows);
         }

         for (var i = 0; i < cols; i++) {

           for (var j = 0; j < rows; j++) {
                theGrid[j][i] = new getTheSpot(j, i);

            }
        } 

    } 
    var s = getTheSpot(9, 2);
    console.log (s);
1
  • 1
    Do you mind showing us what have you tried so far? Commented Mar 1, 2017 at 16:47

1 Answer 1

1

If I understand what you need correctly, you can reference an array element like this:

var your_array = [ 10, 11, 15, 8 ];

// Array indexes start at 0
// array[0] is the the first element
your_array_name[0] == 10
//=> true

// array[2] is the third element
your_array_name[2] == 15
//=> true

Now, on 2D matrixes (arrays inside an array), here's how things go:

var awesome_array = [
    [ 0, 10, 15, 8 ],
    [ 7, 21, 75, 9 ],
    [ 5, 11, 88, 0 ]
];

// Remember the index starts at 0!

// First array, first element
awesome_array[0][0] == 0
//=> true

// Second array, fourth element
awesome_array[1][3] == 9
//=> true

In your case, you (supposedly) have this layout:

var greatest_array = [
    [ "A", "B", "C", "D", "E", "F" ],
    [ "B", "C", "D", "E", "F", "G" ],
    [ "C", "D", "E", "F", "G", "H" ]
];

// Your desired "E" is on the second array (index 1), fourth line (index 3):
console.log(greatest_array[1][3]);  //=> "E"

Cheers!

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.