1

JavaScript multidimensional array length always returning 0, how can I solve this problem?

enter image description here

class test {

  static init() {
    test.arr = [];
  }

  static add() {
    let user_id = Math.floor(Math.random() * 10000);
    if (test.arr["u_" + user_id] === undefined) {
      test.arr["u_" + user_id] = [];
    }
    test.arr["u_" + user_id].push({
      "somedata": "here"
    });
  }

  static length() {
    return test.arr.length;
  }

}
test.init();
test.add();
test.add();
console.log(test.arr.length); //Always returning 0

6
  • is this javascript or typescript? Commented Mar 24, 2019 at 12:04
  • @hien as it is tagged js and includes no typescript specific code, I guess it is JS ? Commented Mar 24, 2019 at 12:06
  • Don't abuse arrays when you need an object, or maybe a Map. Commented Mar 24, 2019 at 13:23
  • possible duplicate of Length of a JavaScript object Commented Mar 24, 2019 at 13:25
  • 1
    @ÇağrıYıldırım See the edit on Jonas' answer. Commented Mar 24, 2019 at 13:27

3 Answers 3

1

An array is a sorted set of numeric key value pairs. "_u" + user_id is not numeric, it's a string, therefore it gets stored as a regular property on the array (it behaves like an object) and not as part of the array itself. If you want to use a key-value storage with a length, use a Map.

 const test = { // no need for a class if you dont have instances
   arr: new Map(), // no need for that unneccessary init
   add() {
    let user_id = Math.floor(Math.random() * 10000);
    if(!this.arr.has("u_" + user_id)) { // I prefer "this" over "test", both work however
      this.arr.set("u_" + user_id, []);
    }
    this.arr.get("u_" + user_id).push({"somedata": "here"});
   },

   length() {
    return this.arr.size; //Note: it is "size" not "length" on a Map
   },
};

Sidenote: arr and test are very bad names.

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

4 Comments

same returning 0
@Çağrı Yıldırım whoops, must have been sleeping while answering, you have to use .get and .set on a Map
You even might want to drop the "u_" prefix and just use the user_id only as the key
@ÇağrıYıldırım Yes, that's still the same code (without using .get() and .set() methods) which doesn't work?
1

An array index can be defined as number only. If you want to get the length of an array, there are two ways to achieve this.

  • You need to define the index as number instead of a string.
  • Make a separate object, add your object ({"somedata": "here"}) into the object and push it into the array. Check the code below.

    let test=[]
    let obj = {}
    let user_id = Math.floor(Math.random() * 10000);
    
    if(obj["u_" + user_id] === undefined) {
      obj["u_" + user_id] = [];
    }
    
    obj["u_" + user_id] = {"somedata": "here"};
    test.push(obj)
    

Hope this will be helpful.

2 Comments

How do I get the length?
You just need to console.log(test.length).
0

Check out the following jsbin I made you. https://jsbin.com/xeqacuf/edit?console

    constructor()
    {
        console.log("new object created");
        this.test = { arr : {} };
    }

It's close to what you are trying to do... Let me know if you need explanation or more help. I'm willing to assist as much as youd like. Notice that I changed the datatype from collection to objectKeyValue which allows you to query the object by key like you wanted.

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.