Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding row and column of a multidimensional array in javascript

I defined an array in javascript like this:

var chessboard = []; 
chessboard.push(["a1", "b1", "c1","d1","e1","f1","g1","h1"]);
chessboard.push(["a2", "b2", "c2","d2","e2", "f2","g2","h2"]);
chessboard.push(["a3", "b3", "c3","d3","e3", "f3","g3","h3"]);
chessboard.push(["a4", "b4", "c4","d4","e4", "f4","g4","h4"]);
chessboard.push(["a5", "b5", "c5","d5","e5", "f5","g5","h5"]);
chessboard.push(["a6", "b6", "c6","d6","e6", "f6","g6","h6"]);
chessboard.push(["a7", "b7", "c7","d7","e7", "f7","g7","h7"]);
chessboard.push(["a8", "b8", "c8","d8","e8", "f8","g8","h8"]);

What I'm struggling to find out is how to find the index if the element is passed.

Example: If I pass "a5" the programme should be able to tell me (row,column) as (4,0)

**CODE:**
<!DOCTYPE html>
<html>
<head>
<title>Javascript Matrix</title>
</head>
<body>
<script>
var chessboard = [];
chessboard.push(["a1", "b1", "c1","d1","e1", "f1","g1","h1"]);
chessboard.push(["a2", "b2", "c2","d2","e2", "f2","g2","h2"]);
chessboard.push(["a3", "b3", "c3","d3","e3", "f3","g3","h3"]);
chessboard.push(["a4", "b4", "c4","d4","e4", "f4","g4","h4"]);
chessboard.push(["a5", "b5", "c5","d5","e5", "f5","g5","h5"]);
chessboard.push(["a6", "b6", "c6","d6","e6", "f6","g6","h6"]);
chessboard.push(["a7", "b7", "c7","d7","e7", "f7","g7","h7"]);
chessboard.push(["a8", "b8", "c8","d8","e8", "f8","g8","h8"]);
alert(chessboard[0][1]); // b1
alert(chessboard[1][0]); // a2
alert(chessboard[3][3]); // d4
alert(chessboard[7][7]); // h8
</script>
</body>
</html>

This is where I am right now.

EDIT2:

Thank you so much everyone :) I feel very happy.

It seems there are multiple ways to it! What I'm trying to do is this >> Find out the (row,column) of two squares. Example: Square 1: a4
Square 2: c7

||x,y|| = row1-row2, column1-column2

Now find out (x,y) from another 8x8 matrix/array. And display data from matrix(x,y).

like image 805
Arun J Avatar asked Dec 13 '25 17:12

Arun J


1 Answers

Since it's a chessboard you can get the info from the element itself, without iterating the board:

function findCoo(el) {
  return [
    el[1] - 1, // the row value - 1
    el[0].codePointAt() - 'a'.codePointAt() // the column ascii value - ascii value of a
  ];
}

console.log("a5", findCoo("a5"));
console.log("d6", findCoo("d6"));
alert("a5" + ' ' + findCoo("a5"));
like image 192
Ori Drori Avatar answered Dec 16 '25 05:12

Ori Drori



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!