Calculate the length of an associative array using JavaScript
Last Updated :
22 May, 2024
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)
OutputApple = 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:
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: Below is the implementation of the above approach
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
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: Below is the implementation of the above approach
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
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: Below is the implementation of the above approach
JavaScript
let obj = {
key1: '1',
key2: '2',
key3: '3'
};
let length = Object.entries(obj).length;
console.log(length);
Using Object.getOwnPropertyNames() and length property
To calculate the length of an associative array using Object.getOwnPropertyNames() and the length`property, retrieve an array of all property names using Object.getOwnPropertyNames(), then get the length of that array using the length property.
Example: In this example we calculates the length of an associative array (object) using Object.getOwnPropertyNames() and the length property. It outputs the number of key-value pairs in the object.
JavaScript
let associativeArray = { key1: 'value1', key2: 'value2' };
let length = Object.getOwnPropertyNames(associativeArray).length;
console.log(length);
Similar Reads
How to Find the Length of an Array in JavaScript ?
JavaScript provides us with several approaches to count the elements within an array. The length of an array lets the developer know whether an element is present in an array or not which helps to manipulate or iterate through each element of the array to perform some operation. Table of Content Usi
3 min read
What are Associative Arrays in JavaScript ?
Associative arrays in JavaScript, commonly referred to as objects, are crucial for storing key-value pairs. This guide explores the concept and usage of associative arrays, providing insights into their benefits and applications. Example: // Creating an associative array (object)let arr= { name: "Ge
2 min read
Find the min/max element of an Array using JavaScript
To find the minimum or maximum element in a JavaScript array, use Math.min or Math.max with the spread operator.JavaScript offers several methods to achieve this, each with its advantages.Using Math.min() and Math.max() Methods The Math object's Math.min() and Math.max() methods are static methods t
2 min read
How to Sort an Array Based on the Length of Each Element in JavaScript?
Imagine you have a list of words or groups of items, and you want to arrange them in order from shortest to longest. This is a pretty common task in JavaScript, especially when working with text or collections of things. By sorting your list in this way, you can make sense of your data and make it e
3 min read
How to calculate the XOR of array elements using JavaScript ?
In this article, we are given an array, and the task is to find the XOR of Array elements using JavaScript. There are two approaches to solve this problem which are discussed below: Method 1: It uses a simple method to access the array elements by an index number and use the loop to find the XOR of
2 min read
How to Get the Longest String in an Array using JavaScript?
Given an array, the task is to get the longest string from the array in JavaScript. Here are a few of the most used techniques discussed with the help of JavaScript. In this article, we will use JavaScript methods to find out the longest string in the array. All approaches are described below with e
5 min read
Create an Array of Given Size in JavaScript
The basic method to create an array is by using the Array constructor. We can initialize an array of certain length just by passing a single integer argument to the JavaScript array constructor. This will create an array of the given size with undefined values.Syntaxcosnt arr = new Array( length );J
3 min read
How to create dynamic length array with numbers and sum the numbers using JavaScript ?
In JavaScript, array is a single variable that is used to store different elements. It is often used when we want to store a list of elements and access them by a single variable. Unlike most languages where the array is a reference to the multiple variables, in JavaScript array is a single variable
2 min read
How to Create an Array of Object Literals in a Loop using JavaScript?
Creating arrays of object literals is a very frequent activity in JavaScript, as often when working with data structures, several objects are needed. This article will allow your hand through different ways of coming up with an array of object literals in a loop in JavaScript. Here are different app
5 min read
How to convert Integer array to String array using JavaScript ?
The task is to convert an integer array to a string array in JavaScript. Here are a few of the most used techniques discussed with the help of JavaScript. Approaches to convert Integer array to String array:Table of ContentApproach 1: using JavaScript array.map() and toString() methodsApproach 2: Us
2 min read