/  Technology   /  Create an associative array in Javascript
Create an associative array in Javascript

Create an associative array in Javascript

 

Arrays are classified into three types:

  1. Indexed arrays
  2. Multidimensional arrays
  3. Associative arrays.

In this article, we’ll talk about associative arrays.

What is an Associative arrays?

Associative arrays are dynamic objects that can be redefined by the user as needed. When you assign values to keys in an Array variable, the array is transformed into an object and loses its Array attributes and methods. Because the variable is no longer of the Array type, the length attribute has no effect.

Associative arrays are used to represent collections of data elements that can be retrieved by specifying a name known as a key.

An associative array is either declared or created dynamically.

We can make it by putting a literal into a variable. 

Syntax:

var arr = { "A": 1, "B": 2, "C": 3 };

In contrast to simple arrays, we use curly braces rather than square brackets.

Whatever method was used to declare the array, the content is accessed by keys.

JavaScript object is also an associative array. Therefore, using the reserved word Object, we can create an associative array and then assign keys and values

 <script>
        var obj = new Object();
        obj["A"] = 1;
        obj["B"] = 2;
        obj["C"] = 3;
        for (var i in obj) {
            document.write(i + "=" + obj[i] + '<br>');
        }
 </script>

Output:

A=1
B=2
C=3

 We can transform an associative array, i.e. an object, into a simple array. With the method that returns the list of keys, and the map method.

 <script>
        var a2 = { "a": 1, "b": 2, "c": 3 }
        var a3 = Object.keys(a2).map(function (k) { return a2[k]; })
        document.write(a3)
 </script>

Output:

1,2,3

 

Leave a comment