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

5 JavaScript console method you should be aware of


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

What is JSON? Know how it Works with Examples


Learn what JSON is and how it works with examples in this comprehensive guide. Discover the basics of JSON syntax, its applications, and why it has be...

What is prototype and prototype chaining in JavaScript


This article explains the concept of prototype and prototype chaining in JavaScript. Learn how prototypes work, how they are used to create inheritanc...

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...

What is the first class function in JavaScript ?


Learn about first-class functions in JavaScript! Find out what they are, how they work, and how they can be used to enhance your coding skills.