How can we calculate the length of the above associative array’s counterArray?

There are no in-built functions and properties available to calculate the length of associative array object here. However, there are other ways by which we can calculate the length of an associative array object. In addition to this, we can also extend an Object by adding a method or property to the prototype in order to calculate length. However, extending an object might break enumeration in various libraries or might create cross-browser issues, so it’s not recommended unless it’s necessary. Again, there are various ways by which we can calculate length.

Object has the keys method which can be used to calculate the length of an object:


We can also calculate the length of an object by iterating through an object and by counting the object's own property.  

```javascript
function getSize(object){
  var count = 0;
  for(key in object){
    // hasOwnProperty method check own property of object
    if(object.hasOwnProperty(key)) count++;
  }
  return count;
}

We can also add a length method directly on Object:

Object.length = function(){
  	var count = 0;
  for(key in object){
    // hasOwnProperty method check own property of object
    if(object.hasOwnProperty(key)) count++;
  }
  return count;
}
//Get the size of any object using
console.log(Object.length(counterArray))
Asked on January 18, 2019 in Javascript.
Add Comment


  • 6 Answer(s)

    One can also deal with the issue of associative arrays length matters by keeping track of the length of the array with a associative element called length.

    aka:

    myArray["length"]=0;

    As you add or remove elements simply add or subtract from the myArrary["length"] element.

    Then you can do things such as:

    theLength=myArray.length;
    Answered on January 19, 2019.
    Add Comment

    There is no built-in property that tells you how many properties the object has .

    The closest I can think of is an ES5 and higher feature, Object.keys (spec | MDN), which you could use like this:

    console.log(Object.keys(quesArr).length); // "3"

    Object.keys returns an array of the names of an object’s own enumerable properties. But internally of course it’s that loop you didn’t want to use (and the polyfill for it for pre-ES5 environments uses a loop, of course).

    There’s also another ES5+ feature, Object.getOwnPropertyNames (spec | MDN), which returns an array of the object’s “own” property names regardless of whether they’re enumerable.

    Both are supported in anything vaguely modern. IE9+, and versions of Chrome, Firefox, and Safari since at least 2011.


    FWIW, unless you’re going to use the Array features of the object, don’t make it an array. Instead:

    var quesArr={};
    quesArr["q101"]="Your name?";
    quesArr["q102"]="Your age?";
    quesArr["q103"]="Your school?";

    Those keys don’t have to be given as string literals in square brackets, either, if you don’t want them to be (whether use use an array or a plain object):

    var quesArr={};
    quesArr.q101="Your name?";
    quesArr.q102="Your age?";
    quesArr.q103="Your school?";

    But you can use the other notation if you prefer; they’re exactly equivalent except that with dotted notation the keys must be valid identifiers (in bracketed notation they can be anything).

    You can even do this:

    var quesArr={
        q101: "Your name?",
        q102: "Your age?",
        q103: "Your school?"
    };

    or (if the keys won’t be valid identifiers):

    var quesArr={
        "q101": "Your name?",
        "q102": "Your age?",
        "q103": "Your school?"
    };
    Answered on January 20, 2019.
    Add Comment

    Associative Arrays in JavaScript are a breed of their own. It is a side effect of the weak typing in JavaScript. To understand the issue, let’s walk through some examples:

    The length property is not defined as it would be in a normal array:

    var basicArray = new Array();
    basicArray[0] = "Portland";
    basicArray[1] = "Beaverton";
    basicArray[2] = "Lake Oswego";
    console.log(basicArray.length);
    // --> Outputs 3, as expected
    
    var associativeArray = new Array();
    associativeArray['city'] = "Portland";
    associativeArray['state'] = "Oregon";
    associativeArray['country'] = "United States";
    console.log(associativeArray.length);
    // --> Outputs 0 in Chrome, what the heck?
    
    // we can also access values through .property notation ?!
    console.log("City is: " + associativeArray['city']);
    console.log("City is: " + associativeArray.city); 
    
    // outputs
    // --> City is: Portland
    // --> City is: Portland
    Answered on January 20, 2019.
    Add Comment

    Suppose you have the following,

    var myObject = {}; // denotes an Object is being created
    myObject.city = “Chennai”;
    myObject.state = “Tamilnadu”;
    myObject.country = “Indian Peninsula”;
    console.log(myObject.length); // results in undefined
    But, there is a way to calculate the length in modern browsers.(Chrome, FF4+, IE9)

    Object.keys(myObject);
    // –> [“city”, “state”, “country”]
    Object.keys(myObject).length
    // –> 3One can also deal with the issue of associative arrays length matters by keeping track of the length of the array with a associative element called length.

    aka:

    myArray[“length”]=0;
    As you add or remove elements simply add or subtract from the myArrary[“length”] element.

    Then you can do things such as:

    theLength=myArray.length;

    Answered on January 27, 2019.
    Add Comment
    string="0123456789"                   # create a string of 10 characters
    array=(0 1 2 3 4 5 6 7 8 9)           # create an indexed array of 10 elements
    declare -A hash
    hash=([one]=1 [two]=2 [three]=3)      # create an associative array of 3 elements
    echo "string length is: ${#string}"   # length of string
    echo "array length is: ${#array[@]}"  # length of array using @ as the index
    echo "array length is: ${#array[*]}"  # length of array using * as the index
    echo "hash length is: ${#hash[@]}"    # length of array using @ as the index
    echo "hash length is: ${#hash[*]}"    # length of array using * as the index

    output:

    string length is: 10
    array length is: 10
    array length is: 10
    hash length is: 3
    hash length is: 3
    Answered on February 5, 2019.
    Add Comment
    Answered on August 7, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.