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
halfer
  • 19,824
  • 17
  • 99
  • 186

3 Answers3

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.

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
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.

Ivar
  • 6,138
  • 12
  • 49
  • 61
Prachi Jain
  • 188
  • 9
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.

UncleFifi
  • 825
  • 1
  • 6
  • 9