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


Recommended Posts

View All

What is a pure function in JavaScript?


Discover what a pure function is in JavaScript and why it's important. Learn how to create and use pure functions to improve your code's reliability.

Difference between Function, Method and Constructor calls in JavaScript


You are probably used to thinking about functions, methods, and class constructors as three distinct things if you are experienced with object-oriente...

5 JavaScript console method you should be aware of


JavaScript includes several fantastic console methods that are less commonly used yet really useful.

Global Variables in JavaScript Explained


Global variables are defined outside of functions or alongside window objects for use throughout the program

What is the purpose of the array slice method


The array slice method is a powerful tool in JavaScript used to extract a section of an array and return a new array. In this article, you'll learn ab...