An associative array.

What is an associative array?

Associative arrays are basic objects in JavaScript where indexes are replaced by user-defined keys. They do not have a length property like a normal array and cannot be traversed using a normal for loop. Refer to more about looping through an associative array in this blog

Syntax and example

var arr = {key1:'value1', key2:'value2'}

Here, arr, is an associative array with key1, key2 being its keys or string indexes and value1 & value 2 are its elements.

var arr = { "Company Name": ‘Expound, "ID": 123}; 

Length of an associative array

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

Object.size = function(arr) {
    var size = 0;
    for (var key in arr) {
        if (arr.hasOwnProperty(key)) size++;
    }
    return size;
};

Now that we have the size method defined, let us use it

var len = Object.size(x);
document.write("Length=" + len);

//Output: Length = 2

Using the keys method

The keys method returns an array of all the attributes, so using this method, we can apply the length attribute of Array.

//Using the previous arr array
document.write("Length=" + Object.keys(arr).length

//Output: Length = 2

Retrieve the elements

To retrieve all the elements of an associative array, one 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

var arr = {
    "Company Name": 'Expound',
    "ID": 123
};
for (var key in arr) {
    var value = arr[key];
    document.write(key + " = " + value + '');
}
//Output: 
Company Name = Expound
ID = 123

Using the keys method

We 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:

var arr = {
    "Company Name": 'Expound',
    "ID": 123
};
var elements = Object.keys(arr).map(function(k) {
    return arr[k];
})
console.log(elements);

//Output: ['Expound', 123]

Thanks for following us If you have any queries leave your comment in the comment box.

Thanks