1

Description:

I am adding the data in my 2D array like the following

my_2d_array['user1'] = {'id':name,'socket':socket};
my_2d_array['user2'] = {'id':name,'socket':socket};

This 2D array keeps the record of all the connected users id and their respective sockets ... I want to display the number of users connected .. So far to do that would be to count the number of rows in the array and display it

I have tried following:

my_2d_array[].length; // this gives nothing 
my_2d_array.length; // this outputs 0 (as number)

What should I do to get the number of rows

UPDATE

I declared my array like this

var my_2d_array = [];
1
  • 1
    how did u declare your array? as array is index based.. so can you please tell us how did u declared it .. that can help us to tell u right and exact answer. Commented Dec 1, 2014 at 4:11

3 Answers 3

6

This could work for you

// initialize
var my_2d_array = {};

// add users
my_2d_array["user1"] = ...
my_2d_array["user2"] = ...

// get number of users
Object.keys(my_2d_array).length;

//=> 2

You should consider using users instead of my_2d_array though. It communicates better and the actual data type is an Object, not specifically an Array.

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

Comments

3

Use push method

my_2d_array.push({'id':name,'socket':socket});
my_2d_array.push({'id':name,'socket':socket});

And my_2d_array.length to get the count

5 Comments

This changes the structure of his data though.
u missed the key ... if I use your method where m I supposed to save the keys e.g did u mean this my_2d_array['user1'].push(...) ??
He updated his question, and it looks like he's not meant to use hash map.
@RksRock Are you new to JavaScript? If you are, then maybe you are using the wrong variable. Seems you want a hash map, which in JS usually implemented as objects ({}), not array ([]).
@RksRock In such case @maček gave a better answer, and you'd better declare var my_2d_array = {};, instead of [].
2

It looks like you are trying to figure out how many keys are in your javascript object my_2d_array.

You should be able to use Object.keys()

Here is a JsFiddle.

var my_2d_array = {};
var name = "Hello";
var socket = "World";
my_2d_array['user1'] = {'id':name,'socket':socket};

var name = "Hello2";
var socket = "World2";
my_2d_array['user2'] = {'id':name,'socket':socket};

alert( Object.keys(my_2d_array).length );

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.