0

I'm working on a discord bot in node js and i need to get the length of the 2 dimentions of a 2d array. My array is structurated like this, that algo get expanded at the bottom when needed:

var users = [["","","","",""]];

now i need to know how to get the dimentions. i was originaly doing like this, but it didn't work 🙃.

// for the y length
users.length

// for the x length
users[i].length

hope you can help

thanks in advance

Enrico 😊

2

3 Answers 3

0

Actually you almost are correct:

var users = [[1,2],[3,4]]
users.length // y
users[0].length // x

Just keeps in mind that index for each X demantion statred since zero , and might be different for each row.

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

Comments

0

Your array var users = [["","","","",""]]; is a 2d array where only the 0th index is occupied. In your case, users[i].length would probably throw a length not defined error of some sort at index 1 and beyond. You should used users[0].length to get the length of the 2d element

Comments

0

Assuming that none of the elements in the array varies its length from the first one you could just get the length of the first element with

var dimensions = [users.length, users[0].length]
// returns [1, 5]

In a more practical world, probably is better for you to get the dimensions on each of the elements on the array users and decide on whether to use the biggest or the smallest, naturally I'll chose the biggest.

var users = [["", "", ""], ["", ""], ["", "", "", ""]];
var elementsLength = users.map((user) => (user.length));
var lengthY = Math.max(...elementsLength);
var lengthX = users.length;
var dimensions = [lengthX, lengthY];
// returns [3, 4]

It all depends on what you want.

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.