Javascript multidimensional array length problem

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

Upvotes: 1

Views: 129

Answers (3)

Prachi Jain
Prachi Jain

Reputation: 188

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.

Upvotes: 1

UncleFifi
UncleFifi

Reputation: 895

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.

Upvotes: 0

Jonas Wilms
Jonas Wilms

Reputation: 138267

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.

Upvotes: 1

Related Questions