Associative arrays are regular arrays in JavaScript where an element is present at a specific index. Associative arrays, on the other hand, are essentially JavaScript objects with user-defined keys in place of the index. Basically, we can say that it stores Key-Value pairs.
Syntax:
let arr = { key1: 'value'1, key2: 'value2', key3: 'value3'}
Key1, Key2, and Key3 are its indexes, and Value1, Value2, and Value3 are its elements. Arr is an associative array in this case.
let arr = {"apple": 10, "grapes": 20};
Method 1
The object contains keys method can be used to determine the object's length.
Object.keys(counterArray).length; // Output 3
Method 2
We can also count the object's own properties while iterating across the object to determine its length. By doing this, we will disregard the following characteristics of the object's prototype chain:
function getLength(object) { var count = 0; for(key in object) { // hasOwnProperty method check own property of object if(object.hasOwnProperty(key)) count++; } return count; }
Method 3
The getOwnPropertyNames method is supported by all current browsers (including IE9+), hence the following code can be used to determine the length:
Object.getOwnPropertyNames(counterArray).length; // Output 3
Method 4
The method size in the Underscore and Lodash libraries is specifically designed to determine the object length. Although using one of these libraries only for the size technique is not something we advise, if it is currently being done in your project, why not?
_.size({one: 1, two: 2, three: 3}); => 3