Friday, September 27, 2024
Google search engine
HomeLanguagesJavascriptCalculate the length of an associative array using JavaScript

Calculate the length of an associative array using JavaScript

In JavaScript, we have normal arrays in which an element is present at a particular index. Whereas Associative arrays are basically Objects in JavaScript where the index is replaced with user-defined keys. Basically, we can say that it stores Key-Value pairs.

Syntax:

let arr = { key1: 'value'1, key2: 'value2', key3: 'value3'}

Here, arr is the associative array, key1, key2, and key3 are its indexes, and value1, value2, and value3 are its elements.

Example: This is a basic example of the associative property.

Javascript




let arr = {
    "apple": 10,
    "grapes": 20
};
arr["guava"] = 30;
arr["banana"] = 40;
console.log("Apple = " + arr.apple)
console.log("Banana = " + arr.banana)


Output

Apple = 10
Banana = 40

 Length of an associative array: Like in a normal array, an associative array does not have a length property. So we will see other ways to calculate the length of associative arrays.

To calculate the length of an associative array, we will traverse the array element and count all the keys present in the array.

We can calculate the length of an associative array in the following ways:

Method 1: Using hasOwnProperty & for…in loop

  • By using for…in loop we can iterate over the object.
  • By checking obj.hasOwnProperty(key), we check it contains only own properties (not inherited) are counted.
  • Increment the size variable for each own property found, which represents the length of the associative array.

Example:

Javascript




// Function to calculate the
// length of an array
sizeOfArray = function (array) {
 
    // A variable to store
    // the size of arrays
    let size = 0;
 
    // Traversing the array
    for (let key in array) {
 
        // Checking if key is present
        // in arrays or not
        if (array.hasOwnProperty(key)) {
            size++;
        }
    }
 
    // Return the size
    return size;
}
 
// Driver code
let arr = { "apple": 10, "grapes": 20 };
arr["guava"] = 30;
arr["banana"] = 40;
 
// Printing the array
console.log(arr);
 
// Printing the size
console.log("size = " + sizeOfArray(arr));
 
// Adding another element to array
arr["fruits"] = 100;
 
// Printing the array and size again
console.log(arr);
console.log("Size = " + sizeOfArray(arr));


Output

{ apple: 10, grapes: 20, guava: 30, banana: 40 }
size = 4
{ apple: 10, grapes: 20, guava: 30, banana: 40, fruits: 100 }
Size = 5

Method 2: Using the keys Method

The keys() method returns an array containing all the keys present in the associative array. So, we can use the length property on this array to get the length of the associative array.

Example:

Javascript




let arr = { "apple": 10, "grapes": 20 };
arr["guava"] = 30;
arr["banana"] = 40;
 
// Printing the array
// returned by keys() method
console.log(Object.keys(arr))
 
// printing the size
console.log("Size = " + Object.keys(arr).length)


Output

[ 'apple', 'grapes', 'guava', 'banana' ]
Size = 4

Method 3: Using Object.entries() Method

JavaScript Object.entries() method is used to return an array consisting of enumerable property [key, value] pairs of the object which are passed as the parameter.By using the length property we can calculate the length of the associative array

Example:

Javascript




let obj = { key1: '1',
            key2: '2',
            key3: '3' };
 
let length = Object.entries(obj).length;
 
console.log(length);


Output

3
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments