Table of Contents
- What is an associative array?
- Syntax & example
- Length of an associative array
- Retrieve the elements of an associative array
- How is it different from a normal array?
- Other Related Concepts
What is an associative array?
Syntax and example
Here, arr, is an associative array with key1, key2 being its keys or string indexes and value1 & value 2 are its elements.
Length of an associative arrayNow that we know how to declare an associative array, let us see how we can calculate its length.
Since we will be no longer able to use the length attribute of the Array object, let us first define a method that returns the size of the array before we use it.
Refer to this article to know more about hasonwnproperty.
Now that we have the size method defined, let us use it
Using the keys methodThe keys method returns an array of all the attributes, so using this method, we can apply the length attribute of Array.
Retrieve the elementsTo retrive all the elements of an associative array, cannot use a simple loop as in the case of a normal array because elements are not accessible by an index. Here’s how we can do it instead
Using the keys methodWe can transform an associative array, ie an object, into a simple array. With the method that returns the list of keys, and the map method (ECMAScript 1.6), we also obtain the values:
How is it different from a normal array?
- Unlike simple arrays, we use curly braces instead of square brackets.
- The content or values of associative arrays is accessed by keys.
- An associative array is an array with string keys rather than numeric keys.
Here, the keys of the associative array are “Company Name” & “ID” whereas in the normall array. The keys or index is 0 & 1
- Associative arrays are dynamic objects that the user redefines as needed. When you assign values to keys in a variable of type Array, the array is transformed into an object, and it loses the attributes and methods of Array.
- The length attribute has no effect because the variable is no longer of the Array type.
- We can create an associative array with the Object reserved word, then and assign keys and values: